2012-03-12 32 views
0

嘗試從繪製上下文創建UIimage。 沒有看到任何東西。我錯過了什麼,或者完全在我的腦海裏?CGContext Ref as UIImage

代碼

- (UIImage *)drawRect:(CGRect)rect { 

    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextMoveToPoint(context, 100, 100); 
    CGContextAddLineToPoint(context, 150, 150); 
    CGContextAddLineToPoint(context, 100, 200); 
    CGContextAddLineToPoint(context, 50, 150); 
    CGContextAddLineToPoint(context, 100, 100); 

    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor); 
    CGContextFillPath(context); 


    // Do your stuff here 
    CGImageRef imgRef = CGBitmapContextCreateImage(context); 
    UIImage* img = [UIImage imageWithCGImage:imgRef]; 
    CGImageRelease(imgRef); 
    CGContextRelease(context); 
    return img; 
} 

回答

1

我猜想這是不是一個視圖-drawRect:方法,因爲返回值是錯誤的。 (-[UIView drawRect:]回報void,不是UIImage*。)

如果上的NSView,這意味着你必須直接調用它,得到的返回值。但這意味着UIKit沒有設置圖形上下文,就像在窗口中調用-drawRect:之前一樣。

因此,您不應該認爲UIGraphicsGetCurrentContext()有效。這可能是零(你檢查?)。

如果你只是想一個圖像:使用UIGraphicsBeginImageContext()創建上下文,然後UIGraphicsGetImageFromCurrentImageContext()提取UIImage(無需中介CGImage),然後UIGraphicsEndImageContext()清理。

如果您試圖捕獲您的視圖所繪製的圖像:修復您的-drawRect:以返回void,並找到一些其他方式將UIImage從視圖中取出 - 將其存儲在ivar中,或發送它給其他某個對象,或者寫到一個文件中,無論你喜歡什麼。

而且(同樣重要):

  1. 不要CGContextRelease(context)。你沒有創建,複製或保留它,所以你不應該釋放它。

  2. 不需要最後CGContextAddLineToPoint()CGContextFillPath將隱式關閉您的路徑。