2015-06-01 87 views
0

我想創建一個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]; 
} 
+0

也許你的mapView是不可見的(不在視圖層次結構中) – Bannings

+0

是否必須將mapView添加到視圖層次結構中?這正是我所要避免的,因爲我不想畫它,只是想要一個圖像。 'renderInContext'可以在不添加視圖層次結構的情況下完成工作,確定'drawViewHierarchyInRect'? – Wingzero

回答

1

-drawViewHierarchyInRect:afterScreenUpdates:,它可以讓你呈現一個快照的完整視圖層次結構在屏幕上可見的成位圖上下文。

renderInContext:直接從CALayer的渲染樹渲染爲有效的Core Graphics上下文。

如果要將視圖呈現爲UIImage而不是在View Hierarchy上顯示它,則應使用renderInContext

+0

好吧,你能解釋一下,如果我使用'UIView * view = [_mapView snapshotViewAfterScreenUpdates:YES];'替換'drawViewHierarchyInRect',我仍然不會將它添加到視圖層次結構中,但是我得到了一個有效的UIView,儘管它是不是圖像。我很困惑,他們是不是以同樣的方式工作? – Wingzero