-1

This code:

    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()

Is throwing these errors:

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 size seems fine, which other posts suggest as the problem. So what else is incorrectly set, please? Thank you.

Community
  • 1
  • 1
Joseph Beuys' Mum
  • 2,395
  • 2
  • 24
  • 50
  • It's saying that the `context` you are giving the CoreGraphics functions is null. This would imply that there is no current context to draw onto. – dreamlax Aug 21 '16 at 21:56

2 Answers2

5

You need to get the current context after you begin the image context.

(Apparently, when you are calling this code, before you call UIGraphicsBeginImageContext(), there is no current context. Therefore 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()
Kurt Revis
  • 27,695
  • 5
  • 68
  • 74
  • Apols @KurtRevis, we both posted the same answer at the same time. It's nearly midnight here and I'm making stupid mistakes. Time for bed I think. Thank you! – Joseph Beuys' Mum Aug 21 '16 at 21:59
0

My bad, these two were simply the wrong way around:

UIGraphicsBeginImageContext( rect.size )
let context = UIGraphicsGetCurrentContext()
Joseph Beuys' Mum
  • 2,395
  • 2
  • 24
  • 50