我有一个 400x320 的 View (testView),我需要截取该 View 的一部分(比如 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();
任何帮助将不胜感激!
谢谢。
最佳答案
在获得整个快照后,您可以按照获得所需部分的方式在较小的图形上下文中绘制它:
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();
关于iOS 7 截取部分 UIView 的屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20558033/