2014-10-31 45 views
1

我編寫了UIImage的這個簡單擴展來繪製從預定義顏色和大小開始的圖像。以編程方式創建UIImage - 代碼錯誤

這是代碼:

extension UIImage { 

    class func image(color:UIColor, size:CGSize)->UIImage { 

     UIGraphicsBeginImageContextWithOptions(size, true, 2.0); 

     let context = UIGraphicsGetCurrentContext() 
     let rect = CGRectMake(0, 0, size.width, size.height) 

     color.set() 

     CGContextFillRect(context, rect) 
     var image = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 

     return image 
    } 
} 

如果我在一個控制器的viewDidLoad方法推出這個代碼,我得到這個錯誤

Oct 31 16:48:02 iPhone Budjet_v2[3387] <Error>: CGContextSetFillColorWithColor: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update. 
Oct 31 16:48:02 iPhone Budjet_v2[3387] <Error>: CGContextSetStrokeColorWithColor: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update. 
Oct 31 16:48:02 iPhone Budjet_v2[3387] <Error>: CGContextFillRects: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update. 
fatal error: unexpectedly found nil while unwrapping an Optional value 

我不明白這有什麼錯我的代碼。

+0

你的代碼發佈 – 2014-10-31 16:48:23

+0

模糊的想法:在viewDidLoad中可能沒有CGContext?我很好奇如果你從viewDidAppear嘗試它會發生什麼;也許在實際繪製東西之前沒有CGContext 。 – 2014-10-31 21:33:13

回答

1

這似乎是iOS 7中引入的錯誤。在答案here中列出了創建此錯誤的方法的完整列表。

從這個問題的建議的行動方針是添加一個符號斷點CGPostError來分析堆棧,當這個錯誤發生,以確定什麼是觸發這個錯誤。

這個錯誤可能會觸發多種情況,無法進一步研究就無法確定哪些情景觸發了錯誤。

祝你好運!

1
if (!(CGSizeEqualToSize(size, CGSizeZero))){ 

    // your drawing code.... 

    }else{ 


return nil; 

} 

(這顯然ObjC,道歉,我還沒有一個成功的迅速投石.... 我懷疑你的問題是大小的情況下(0,0)