我想为UIView创建快照图像,我曾经使用renderInRect,但是它很慢,而且我发现drawViewHierarchyInRect是iOS 7以后的较新API,所以我想尝试一下。
我在下面的代码中编写代码,但它从未创建有效的图像,而只是创建空白图像。
-(void)drawRect:(CGRect)rect {
UIGraphicsBeginImageContextWithOptions(_mapView.bounds.size, _mapView.opaque, [[UIScreen mainScreen] scale]);
CGContextRef context = UIGraphicsGetCurrentContext();
// Used to use renderInContext, but it's slow
// [mapView.layer renderInContext:context];
[_mapView drawViewHierarchyInRect:_mapView.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.thumbImageView = [[UIImageView alloc] initWithImage:image];
[self addSubview:self.thumbImageView];
}
最佳答案
-drawViewHierarchyInRect:afterScreenUpdates:
,可让您在位图上下文中在屏幕上可见时呈现完整视图层次结构的快照。renderInContext:
直接从CALayer的渲染树渲染到有效的Core Graphics上下文。
如果要将视图呈现到UIImage,而不是将其呈现在视图层次结构中,则应使用renderInContext
。
关于ios - 如何使用drawViewHierarchyInRect,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30565092/