为什么 CGContextSetFillColorWithColor 和 CGContextFillRects 都抛出 "invalid context 0x0" 错误?

Why do CGContextSetFillColorWithColor and CGContextFillRects both throw "invalid context 0x0" error?

此代码:

    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 建议这是问题所在。那么还有什么设置不正确,请问?谢谢你。

您需要在开始图像上下文后获取当前上下文。

(显然,当您调用此代码时,在调用 UIGraphicsBeginImageContext() 之前,没有当前上下文。因此 UIGraphicsGetCurrentContext() returns 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()

我的错,这两个完全是错误的方式:

UIGraphicsBeginImageContext( rect.size )
let context = UIGraphicsGetCurrentContext()