2016-08-21 93 views
-1

此代碼:爲什麼CGContextSetFillColorWithColor和CGContextFillRects都拋出「無效的情況下爲0x0」的錯誤?

let rect = CGRectMake(0.0, 0.0, 16.0, 16.0) 
    let context = UIGraphicsGetCurrentContext() 

    UIGraphicsBeginImageContext(rect.size) 
    CGContextSetFillColorWithColor(context, color.CGColor) 
    CGContextFillRect(context, rect) 

    let image = UIGraphicsGetImageFromCurrentImageContext() 

    UIGraphicsEndImageContext() 

拋出這些錯誤:

MakeImage[60890] <Error>: CGContextSetFillColorWithColor: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable. 
MakeImage[60890] <Error>: CGContextFillRects: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable. 

的CGRect大小似乎罰款,這other posts建議的問題。那麼還有什麼設置不正確,好嗎?謝謝。

+0

這就是說你給CoreGraphics函數的'context'是null。這將意味着,沒有當前上下文上繪製。 – dreamlax

回答

4

你需要獲得當前上下文後開始圖像內容。

(很顯然,當你調用這個代碼,你叫UIGraphicsBeginImageContext()之前,沒有當前上下文因此UIGraphicsGetCurrentContext()返回nil)。

let rect = CGRectMake(0.0, 0.0, 16.0, 16.0) 
UIGraphicsBeginImageContext(rect.size) 

let context = UIGraphicsGetCurrentContext() 

CGContextSetFillColorWithColor(context, color.CGColor) 
CGContextFillRect(context, rect) 

let image = UIGraphicsGetImageFromCurrentImageContext() 

UIGraphicsEndImageContext() 
+0

Apols @KurtRevis,我們都貼出了同樣的答案在同一時間。這是近午夜這裏,我做愚蠢的錯誤。我想睡覺的時候了。謝謝! –

0

我的壞,這兩個是根本錯誤的周圍方式:

UIGraphicsBeginImageContext(rect.size) 
let context = UIGraphicsGetCurrentContext() 
相關問題