截图只是屏幕的一部分 - 斯威夫特

tdh*_*tdh 16 screenshot fullscreen ios swift

我正在使用此Swift代码截取我的应用程序的屏幕截图:

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

UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

我如何才能截取屏幕的一部分,而不是全部,就像我在这里一样?

rak*_*hbs 33

例如,如果要将UIView矩形的屏幕截图放在(50,50)高度为的位置(100,150).

首先将图像上下文设置为矩形的大小.这会设置图像大小.

UIGraphicsBeginImageContextWithOptions(CGSizeMake(100,150), false, 0);
Run Code Online (Sandbox Code Playgroud)

现在以这样一种方式在这个上下文中绘制视图,截屏可见部分开始于(50,50)

self.view.drawViewHierarchyInRect(CGRectMake(-50,-50,view.bounds.size.width,view.bounds.size.height) afterScreenUpdates: true)
Run Code Online (Sandbox Code Playgroud)

这会剪切屏幕截图,(100,150)因为我们设置了我们的尺寸context.现在从中获取UIImage.

var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
Run Code Online (Sandbox Code Playgroud)