我想創建一個UIView的快照圖像,我曾經使用renderInRect,但速度很慢,而且我發現drawViewHierarchyInRect是iOS 7以後的一個更新的API,所以我想試試它。如何使用drawViewHierarchyInRect
我寫下面的代碼,但它永遠不會創建一個有效的圖像,只是一個空白圖像。
-(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];
}
也許你的mapView是不可見的(不在視圖層次結構中) – Bannings
是否必須將mapView添加到視圖層次結構中?這正是我所要避免的,因爲我不想畫它,只是想要一個圖像。 'renderInContext'可以在不添加視圖層次結構的情況下完成工作,確定'drawViewHierarchyInRect'? – Wingzero