问题描述
我正在使用此Swift代码截取我的应用程序的屏幕截图:
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?
推荐答案
例如,如果你想拍摄 UIView的屏幕截图/ code>位于
的矩形(50,50)
,高度(100,150)
。
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);
现在在这个上下文中绘制视图,其中可见部分截图以(50,50)开头
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)
这会截断(100,150)
的屏幕截图,因为我们设置了上下文的大小
。现在从中获取UIImage。
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();
这篇关于截图只是屏幕的一部分 - 斯威夫特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!