Screenshot Only Part of Screen - Swift

那年仲夏 提交于 2019-12-20 11:48:11

问题


I'm using this Swift code to take a screenshot of my app:

UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, 0);
self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

How would I go about taking a screenshot of only part of the screen, and not all of it, as I do here?


回答1:


For example if you want to take the screen shot of the UIView rectangle at position (50,50) with height of (100,150).

First set the Image Context to the size of the rectangle. This sets the image size.

UIGraphicsBeginImageContextWithOptions(CGSizeMake(100,150), false, 0);

Now draw the view in this context in such a way that, the visible part of the screenshot starts at (50,50)

self.view.drawViewHierarchyInRect(CGRectMake(-50,-50,view.bounds.size.width,view.bounds.size.height) afterScreenUpdates: true)

This clips the screen shot at (100,150) because we set the size of our context. Now take the UIImage from this.

var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();



回答2:


To snapshot a view containing a UIVisualEffect (Blur/Vibrancy), see my solution here: https://stackoverflow.com/a/33633386/802196




回答3:


I think this is the best Answer to take a shot of part of the screen:

func screenShot() {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.frame.size.width*0.99,self.frame.size.height*0.70), false, 0)
    var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
    self.view?.drawViewHierarchyInRect(CGRectMake(-01, -01, self.frame.size.width, self.frame.size.height), afterScreenUpdates: true)
    var screenShot  = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}



回答4:


for taking a snapshot selecting by area of another UIView

// viewObject: UIView linked from storyboard
var bounds= CGRect(x: -viewObject.frame.minX,y: -viewObject.frame.minY,width: view.bounds.size.width,height: view.bounds.size.height)

UIGraphicsBeginImageContext(viewObject.frame.size)
        view.drawHierarchy(in: bounds, afterScreenUpdates: true)
        let outputImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()


来源:https://stackoverflow.com/questions/27975954/screenshot-only-part-of-screen-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!