I am trying to add a shadow to my UIView, but in my drawRect method I get an EXC_BAD_ACCESS. (I am using ARC)
-(void) drawRect:(CGRect)rect {
CGColorRef lightColor = [UIColor colorWithRed:105.0f/255.0f green:179.0f/255.0f blue:216.0f/255.0f alpha:0.8].CGColor;
CGColorRef shadowColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.4].CGColor;
CGContextRef context = UIGraphicsGetCurrentContext();
// Draw shadow
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, CGSizeMake(-5, 0), 10, shadowColor);
CGContextSetFillColorWithColor(context, lightColor);
CGContextFillRect(context, _coloredBoxRect);
CGContextRestoreGState(context);
}
Error Message: Thread 1: Program received signal: "EXC_BAD_ACCESS".
Line: CGContextSetFillColorWithColor(context, lightColor);
When I change this line to:
[[UIColor colorWithRed:105.0f/255.0f green:179.0f/255.0f blue:216.0f/255.0f alpha:0.8] setFill];
I get the same error but on this line:
CGContextSetShadowWithColor(context, CGSizeMake(-5, 0), 10, shadowColor);
Update I finally resolved the issue by changing:
CGColorRef shadowColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.4].CGColor;
to
float components[4] = {0, 0, 0, 1.0/3.0}; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGColorRef shadowColor = CGColorCreate( colorSpace, components);
The eventual (working) code:
-(void) drawRect:(CGRect)rect
{
float components[4] = {0, 0, 0, 1.0/3.0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGColorRef shadowColor = CGColorCreate( colorSpace, components);
CGContextRef context = UIGraphicsGetCurrentContext();
// Draw shadow
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, CGSizeMake(-5, 0), 10, shadowColor);
CGContextSetFillColorWithColor(context, lightColor);
[[UIColor colorWithRed:105.0f/255.0f green:179.0f/255.0f blue:216.0f/255.0f alpha:0.8] setFill];
CGContextRestoreGState(context);
}