Search code examples
ioscore-graphicsexc-bad-accessalphauicolor

Trying to set color with alpha crashes


I'm trying to set the fill UIColor to have alpha

glassColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.3].CGColor;
CGContextSetFillColorWithColor(context, glassColor);
...

The second line crashes with EXC_BAD_ACCESS.

Any ideas as to why ?


Solution

  • Essentially your problem is that ARC is releasing the UIColor as it is not being used. You need to retain the CGColor structure. You can do it the following way.

     CGColorRef aColorRef = CGColorRetain([[UIColor colorWithWhite:0.82 alpha:1.0] CGColor] );
     CGContextSetFillColorWithColor(context, aColorRef);
    

    And don't forget to release it once you are done using it:

     CGColorRelease(aColorRef);