I'm trying to draw a shadow under the bottom edge of a UIView
in Cocoa Touch. I understand that I should use CGContextSetShadow()
to draw the shadow, but the Quartz 2D programming guide is a little vague:
CGContextSetShadow
, passing the appropriate values.I've tried the following in a UIView
subclass:
- (void)drawRect:(CGRect)rect { CGContextRef currentContext = UIGraphicsGetCurrentContext(); CGContextSaveGState(currentContext); CGContextSetShadow(currentContext, CGSizeMake(-15, 20), 5); CGContextRestoreGState(currentContext); [super drawRect: rect]; }
..but this doesn't work for me and I'm a bit stuck about (a) where to go next and (b) if there's anything I need to do to my UIView
to make this work?
Add subview with the same color which will be centered on the parent and will be with several pixels smaller. Like this you will have space from each side of the parent. On the parent turn on clipping subviews and add shadow to the inner view. Like this, you can have an inner shadow.
Go to the Storyboard. Add a Button to the main view and give it a title of "Shadow Tutorial". Select the Resolve Auto Layout Issues button and select Reset to Suggested Constraints. The Storyboard should look like this.
A by far easier approach is to set some layer attributes of the view on initialization:
self.layer.masksToBounds = NO; self.layer.shadowOffset = CGSizeMake(-15, 20); self.layer.shadowRadius = 5; self.layer.shadowOpacity = 0.5;
You need to import QuartzCore.
#import <QuartzCore/QuartzCore.h>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With