Core Animation: Adding Drop Shadows to A Contexton 9 February 2011

I have recently dove head-first into iOS development again. The main function thus far has been to learn about the Core Graphics APIs and programmatically draw for quick rendering, especially in UITableViewCells. There is going to be a lot of data that is going to be compared or expressed visually that will be custom for each cell. Therefore rendering speed is key.

The prevalent effect is drop shadowed text. This has been easy to implement. So I am doing all of my custom drawing in the drawRect: method that is overwritten in the custom UITableViewCell.

- (void)drawRect:(CGRect)rect {
  CGContextRef ctx = UIGraphicsGetCurrentContext();

  CGContextSetShadowWithColor(ctx, CGSizeMake(2.0f, 2.0f), 1.0f, [[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:.6] CGColor]);

  [stringText drawInRect:CGRectMake(0.0, 0.0, 200.0, 40.0) withFont:[UIFont fontWithName:@"HelveticaNeue" size:16.0] lineBreakMode:UILineBreakModeClip alignment:UITextAlignmentLeft];

  //Clear Shadow context
  //CGContextSetShadowWithColor(context, CGSizeMake(0.0, 0.0), 0.0, nil);
}

The first line of drawRect: grabs the current drawing context and assign it to ctx. CGContextSetShadowWithColor will set the shadow to the context. with an offset of 2.0 to the bottom and the right, assigns a blur of 1.0 pixel and the CGColor of a UIColor object. Any subsequent drawing to the context will result in a drop shadow being applied to that element.

The third line draws the value of stringText to the context with the drop shadow parameters specified.

Using the current context and setting a shadow with the CGContextSetShadowWithColor method, will draw a shadow with the specified size and color to any drawn item that follows. This includes text, images and drawn shapes.

Drop shadow applied

If you enjoyed this, use this shorter link to share: http://the.ichibod.com/s/cads