在swift中截取Textfield的截图?

时间:2015-02-06 11:22:39

标签: ios swift

制作iOS应用程序,捕获填充了某些图像的textview的屏幕截图。问题是屏幕截图捕获整个屏幕。 如何使用Swift拍摄UITextView的屏幕截图?

3 个答案:

答案 0 :(得分:1)

您可以使用drawViewHierarchyInRect方法

将任何视图保存为图像
UIGraphicsBeginImageContextWithOptions(self.textView.bounds.size, false, 0);
self.textText.drawViewHierarchyInRect(CGRectMake(0, 0, self.textView.frame.size.width, self.textView.frame.size.height),afterScreenUpdates:true)
var screenShot:UIImage = UIGraphicsGetImageFromCurrentImageContext();

答案 1 :(得分:1)

以下为我工作

UIGraphicsBeginImageContextWithOptions(self.textField.bounds.size, false, 0);
self.textField.drawViewHierarchyInRect(self.textField.bounds, afterScreenUpdates: true)
let copied = UIGraphicsGetImageFromCurrentImageContext();
imageView.image = copied
UIGraphicsEndImageContext();

答案 2 :(得分:0)

所有答案都很好,但遗失的是scale necessary context

使用UIView's drawViewHierarchyInRect mehtod捕获屏幕。

//Use screen scale for better images
let screenScale = UIScreen.mainScreen().scale;
//create context 
UIGraphicsBeginImageContextWithOptions(yourView.bounds.size, false, screenScale);
//use view for drawing
yourView.drawViewHierarchyInRect(yourView.bounds, afterScreenUpdates: true)
//get captured image
let capturedImage = UIGraphicsGetImageFromCurrentImageContext();
//last dump context
UIGraphicsEndImageContext();

另一个诽谤:使用UIView's layer's renderInContext

//Use screen scale for better images
let screenScale = UIScreen.mainScreen().scale;
//create context 
UIGraphicsBeginImageContextWithOptions(yourView.bounds.size, false, screenScale);
//use view for drawing
yourView.layer.renderInContext(UIGraphicsGetCurrentContext())
//get captured image
let capturedImage = UIGraphicsGetImageFromCurrentImageContext();
//last dump context
UIGraphicsEndImageContext();