2012-11-01 22 views
1

當我有以下的方法,我正在嘗試做一些繪製成圖像:正確GraphicsContext使用UIGraphicsGetImageFromCurrentImageContext

- (UIImage*) renderImage 
{ 
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    //drawing code 

    UIImage *image = [UIGraphicsGetImageFromCurrentImageContext() retain]; 
    UIGraphicsEndImageContext(); 
    return [image autorelease];  
} 

當我運行這段代碼我注意到,我就要比我打更難當我簡單地在的UIView中畫出這個代碼的時候。我在這裏畫錯了圖形上下文(即CGContextRef context = UIGraphicsGetCurrentContext();)?或者是UIGraphicsGetImageFromCurrentImageContext只比drawRect中的圖紙貴多了?

+0

好問題,我會說它分配更多的內存,因爲你現在繪製到視圖*加*獲取圖像的副本。 – 2012-11-01 09:14:38

+0

有些東西看起來不正確,我正在加載圖像的桌面視圖,速度慢了2-3倍。 –

+0

我在UIGraphicsGetCurrentContext的文檔中發現了這個問題:「當前的圖形上下文默認爲零,在調用它的drawRect:方法之前,視圖對象將一個有效的上下文推送到堆棧上,使其成爲最新的如果你沒有使用UIView對象要執行繪圖,但是,必須使用UIGraphicsPushContext函數手動將有效上下文推送到堆棧上。「 –

回答

0

主要區別在於您創建的上下文需要離屏渲染,它與-drawRect中創建的上下文不同。因此,您要添加額外的內存,直到您釋放圖像爲止。