Shadows

To add a shadow to a drawing, give the context a shadow value before drawing. The shadow position is expressed as a CGSize, where the positive direction for both values indicates down and to the right. The blur value is an open-ended positive number; Apple doesn’t explain how the scale works, but experimentation shows that 12 is nice and blurry, 99 is so blurry as to be shapeless, and higher values become problematic.

Figure 15-17 shows the result of the same code that generated Figure 15-16, except that before we start drawing the arrow repeatedly, we give the context a shadow:

con = UIGraphicsGetCurrentContext();
CGContextSetShadow(con, CGSizeMake(7, 7), 12);
[im drawAtPoint:CGPointMake(0,0)]; // ... and so on
Drawing with a shadow
Figure 15-17. Drawing with a shadow

However, there’s a subtle cosmetic problem with this approach. It may not be evident from Figure 15-17, but we are adding a shadow each time we draw. Thus the arrows are able to cast shadows on one another. What we want, however, is for all the arrows to cast a single shadow collectively. The way to achieve this is with a transparency layer; this is basically a subcontext that accumulates all drawing and then adds the shadow. Our code for drawing the shadowed arrows would thus look like this:

CGContextSetShadow(con, CGSizeMake(7, 7), 12); CGContextBeginTransparencyLayer(con, nil); [im drawAtPoint:CGPointMake(0,0)]; for (int i=0; i<3; ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.