Search code examples
iosobjective-ccore-graphicsquartz-2d

Quartz 2D Drawing Crashing


I don't know why this stopped working, but this chunk of code is crashing my device when I try drawing any part of it. I'm new to core graphics so any pointers or suggestions would be a great help. Thanks!

// Style
CGContextRef context = UIGraphicsGetCurrentContext();

// Colors
CGColorRef fillBox = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0].CGColor;
CGColorRef fillBoxShadow = [UIColor colorWithRed:77.0/255.0 green:77.0/255.0 blue:77.0/255.0 alpha:1.0].CGColor;

CGRect box = CGRectMake(5, 5, self.frame.size.width - 10, self.frame.size.height - 10);
// Shadow
CGContextSetShadowWithColor(context, CGSizeMake(0, 0), 1.0, fillBoxShadow);
CGContextAddRect(context, box);
CGContextFillPath(context);
// Box
CGContextSetFillColorWithColor(context, fillBox);
CGContextAddRect(context, box);

CGContextFillPath(context);

Solution

  • If your project is using ARC, then these two lines might be part of your problem:

    CGColorRef fillBox = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0].CGColor;
    CGColorRef fillBoxShadow = [UIColor colorWithRed:77.0/255.0 green:77.0/255.0 blue:77.0/255.0 alpha:1.0].CGColor;
    

    ARC is releasing the UIColor object and thus the CGColorRef. You need to retain the CGColorRef and then release it when you are done with it.

    I would write the code something like this:

    UIColor *fillBox = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0];
    UIColor *fillBoxShadow = [UIColor colorWithRed:77.0/255.0 green:77.0/255.0 blue:77.0/255.0 alpha:1.0];
    

    and then use fillBox.CGColor and fillBoxShadow.CGColor later on in the method.