如何使用drawViewHierarchyInRect

时间:2015-06-01 03:08:52

标签: ios

我想为UIView创建快照图像,我以前使用renderInRect,但它很慢,我发现自从iOS 7以来,drawViewHierarchyInRect是一个较新的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];
}

1 个答案:

答案 0 :(得分:1)

-drawViewHierarchyInRect:afterScreenUpdates:,可让您将整个视图层次结构的 快照 呈现为屏幕上可见的位图上下文。

renderInContext:直接从CALayer的渲染树渲染到有效的Core Graphics上下文。

如果要将视图呈现给UIImage而不是将其呈现在视图层次结构上,则应使用renderInContext