仅截取屏幕的一部分截图 - Swift

20
我正在使用以下 Swift 代码来截取我的应用程序的屏幕截图:
UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, 0);
self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

我该如何截取屏幕的一部分,而不是像我在这里做的那样截取整个屏幕?

4个回答

43
例如,如果您想在位置(50,50)处以高度(100,150)获取UIView矩形的屏幕截图。首先将图像上下文设置为矩形的大小。这将设置图像大小。
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100,150), false, 0);

现在以这个上下文为基础绘制视图,使得 截屏的可见部分(50,50) 开始。

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

这会剪裁屏幕截图在 (100,150) 处,因为我们设置了 context 的大小。现在从中获取UIImage。

var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();

谢谢您的快速回答! - tdh
mama nuvvu keka mama ;) - chandu
对我不起作用。您介意看一下我的代码吗?http://stackoverflow.com/questions/34887164/how-to-screenshot-just-part-of-a-screen - swiftyboi
1
在Swift 5中,请使用CGRect而不是CGRectmake,例如:CGRect(x: -50,y: -50,width: view.bounds.size.width,height: view.bounds.size.height)。 - Nic Wanavit
有人能解释一下为什么要将原点的 x 和 y 坐标都乘以 -1 吗?难道不应该只是 y 轴吗? - slow
你能解释一下为什么否定是必要的吗? - gran_profaci

1

我认为这是截取屏幕部分的最佳方法:

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()
}

0
func captureView(view: UIView) -> UIImage {
    var screenRect: CGRect = view.bounds
    UIGraphicsBeginImageContext(screenRect.size)
    UIGraphicsBeginImageContextWithOptions(screenRect.size, true, 0)
    var ctx: CGContext = UIGraphicsGetCurrentContext()!
    UIColor.black.set()
    ctx.fill(screenRect)
    view.layer.render(in: ctx)
    var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return newImage
}

0

用于选择另一个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()

你能解释一下为什么否定是必要的吗? - gran_profaci

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接