2013-12-13 65 views
20

我有一个视图(testView)是400x320,我需要截取此视图的一部分(比如rect =(50,50,200,200))。 我正在玩iOS 7中的drawViewHierarchy方法,但我无法弄清楚如何正确地做到这一点。iOS 7截取部分UIView的屏幕截图

UIGraphicsBeginImageContextWithOptions(self.testView.bounds.size, NO, [UIScreen mainScreen].scale); 

    [self.testView drawViewHierarchyInRect:self.testView.bounds afterScreenUpdates:YES]; 

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

任何帮助将不胜感激!

谢谢。

回答

34

得到整个快照后,你可以借鉴它在一个较小的图形上下文中,你得到你想要的部分方式:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), YES, [UIScreen mainScreen].scale); 
[image drawInRect:CGRectMake(-50, -50, image.size.width, image.size.height)]; 
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

编辑:更重要的是,直接绘制的分层结构,该较小的上下文:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), NO, [UIScreen mainScreen].scale); 
[self.testView drawViewHierarchyInRect:CGRectMake(-50, -50, self.testView.bounds.size.width, self.testView.bounds.size.height) afterScreenUpdates:YES]; 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
+0

谢谢!这帮了我很多! – Max

+0

在Swift中使用'self.hostView.superview!.drawHierarchy(in:frame,afterScreenUpdates:true)'其中'frame'肯定小于'superView',我仍然可以看到完整视图的内容。但它压缩到我提供给'UIGraphicsBeginImageContextWithOptions()'(我当然与我的'frame'的'size'相同)的'CGSize'。 –

+1

@意义 - 这里的技巧是通过使用与您的视图完全相同的大小(以防止缩放)来绘制层次结构,并抵消它以获得所需的部分。通过使用'UIGraphicsBeginImageContextWithOptions(CGSize(width:200,height:200),true,0)',你可以用view.drawHierarchy(in:view.bounds,afterScreenUpdates:true)得到视图的左上角200x200部分' 。你也可以通过这种方式来抵消零件:'view.drawHierarchy(in:UIEdgeInsetsInsetRect(view.bounds,UIEdgeInsets(top:-100,left:-100,bottom:0,right:0)),afterScreenUpdates:true) '。希望能帮助到你! – Rufel

0

尝试下面的代码行,

UIView *popSnapshot=[inputView snapshotViewAfterScreenUpdates:YES];