Drawing a gradient-filled rounded rect with a drop shadow

This is something I’ve been fiddling with for the past few hours trying to get to work right. I tried doing stuff with CoreGraphics, drawing paths, drawing images, and so on, but it never quite worked correctly. Then I stumbled upon this post over at cimgf.com, which helped me figure it out.

In a custom UIView subclass, I have this:

- (void) awakeFromNib {
  //turning off bounds clipping allows the shadow to extend beyond the rect of the view
  [self setClipsToBounds:NO];

  //the colors for the gradient.  highColor is at the top, lowColor as at the bottom
  UIColor * highColor = [UIColor colorWithWhite:1.000 alpha:1.000];
  UIColor * lowColor = [UIColor colorWithRed:0.851 green:0.859 blue:0.867 alpha:1.000];

  //The gradient, simply enough.  It is a rectangle
  CAGradientLayer * gradient = [CAGradientLayer layer];
  [gradient setFrame:[self bounds]];
  [gradient setColors:[NSArray arrayWithObjects:(id)[highColor CGColor], (id)[lowColor CGColor], nil]];

  //the rounded rect, with a corner radius of 6 points.
  //this *does* maskToBounds so that any sublayers are masked
  //this allows the gradient to appear to have rounded corners
  CALayer * roundRect = [CALayer layer];
  [roundRect setFrame:[self bounds]];
  [roundRect setCornerRadius:6.0f];
  [roundRect setMasksToBounds:YES];
  [roundRect addSublayer:gradient];

  //add the rounded rect layer underneath all other layers of the view
  [[self layer] insertSublayer:roundRect atIndex:0];

  //set the shadow on the view's layer
  [[self layer] setShadowColor:[[UIColor blackColor] CGColor]];
  [[self layer] setShadowOffset:CGSizeMake(0, 6)];
  [[self layer] setShadowOpacity:1.0];
  [[self layer] setShadowRadius:10.0];

This works perfectly. :)

  1. funwithobjc posted this
Short URL for this post: http://tmblr.co/Zt522y1OOBB6
blog comments powered by Disqus