I have a delegate method of a UIVIew and in the drawRect method I add in a UIBezierPath to show a shadow on a square.
//// General Declarations
CGContextRef context = UIGraphicsGetCurrentContext();
//// Shadow Declarations
UIColor* shadow = [UIColor blackColor];
CGSize shadowOffset = CGSizeMake(0, -0);
CGFloat shadowBlurRadius = 15;
//// Rectangle Drawing
rectanglePath = [UIBezierPath bezierPathWithRect: CGRectMake(8, 8, 44, 44)];
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, shadow.CGColor);
[[UIColor whiteColor] setFill];
[rectanglePath fill];
CGContextRestoreGState(context);
I then want to change the colour of the shadow based on certain criteria so I mave a method called makeRed.
- (void)makeRed {
NSLog(@"makeRed");
CGContextRef context = UIGraphicsGetCurrentContext();
// Shadow Declarations
UIColor* shadow = [UIColor redColor];
CGSize shadowOffset = CGSizeMake(0, -0);
CGFloat shadowBlurRadius = 15;
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, shadow.CGColor);
[[UIColor whiteColor] setFill];
[rectanglePath fill];
CGContextRestoreGState(context);
}
But when I call the method I get the message:
: CGContextSaveGState: invalid context 0x0
any ideas how I can either set the right context or change the shadow colour in a different way?
Note the initial drawing of the shadow works perfectly, as there are other attributes to the delegate i.e. some fancy animations using the .layer method of creating shadows wont work.
Cheers
In the UIView docs you can see
drawRect:So the drawing you do inside
drawRect:is correct as the drawing context is setup correctly etc, this is not the case in yourmakeRedmethod.I would suggest having an ivar
shadowColorand then use this inside yourdrawRect:method.Your
makeRedwould then look like thisand then modify the line in
drawRect:tosetNeedsDisplayis used to tellUIKitthat you would like your view to be redrawn, which then results indrawRect:being called again.You will of course have to initialize
_shadowColor = [UIColor blackColor]in theinit*method.