iOS 7截取UIView的一部分截图

我有一个视图(testView)是400×320,我需要截取这个视图的一部分(比如rect =(50,50,200,200))。 我正在玩iOS 7中的drawViewHierarchy方法,但我不知道如何正确地做到这一点。

UIGraphicsBeginImageContextWithOptions(self.testView.bounds.size, NO, [UIScreen mainScreen].scale); [self.testView drawViewHierarchyInRect:self.testView.bounds afterScreenUpdates:YES]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

任何帮助将不胜感激!

谢谢。

在获得完整的快照之后,可以用一个更小的graphics上下文(Graphic Context)来绘制它,以获得你想要的部分:

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

尝试下面的代码行,

 UIView *popSnapshot=[inputView snapshotViewAfterScreenUpdates:YES];