Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I draw a shadow under a UIView?

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:

  1. Save the graphics state.
  2. Call the function CGContextSetShadow, passing the appropriate values.
  3. Perform all the drawing to which you want to apply shadows.
  4. Restore the graphics state

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?

like image 514
Fraser Speirs Avatar asked Apr 30 '09 08:04

Fraser Speirs


People also ask

How do I add inner shadow to UIView with rounded corners?

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.

How do you add a shadow to a storyboard?

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.


1 Answers

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> 
like image 156
0llie Avatar answered Oct 11 '22 09:10

0llie