Gradients

Gradients can range from the simple to the complex. A simple gradient (which is all I’ll describe here) is determined by a color at one endpoint along with a color at the other endpoint, plus (optionally) colors at intermediate points; the gradient is then painted either linearly between two points in the context or radially between two circles in the context.

You can’t use a gradient as a path’s fill color, but you can restrict a gradient to a path’s shape by clipping, which amounts to the same thing.

To illustrate, I’ll redraw our arrow, using a linear gradient as the “shaft” of the arrow (Figure 15-6):

// obtain the current graphics context CGContextRef con = UIGraphicsGetCurrentContext(); CGContextSaveGState(con); // punch triangular hole in context clipping region CGContextMoveToPoint(con, 90, 100); CGContextAddLineToPoint(con, 100, 90); CGContextAddLineToPoint(con, 110, 100); CGContextClosePath(con); CGContextAddRect(con, CGContextGetClipBoundingBox(con)); CGContextEOClip(con); // draw the vertical line, add its shape to the clipping region CGContextMoveToPoint(con, 100, 100); CGContextAddLineToPoint(con, 100, 19); CGContextSetLineWidth(con, 20); CGContextReplacePathWithStrokedPath(con); CGContextClip(con); // draw the gradient CGFloat locs[3] = { 0.0, 0.5, 1.0 }; CGFloat colors[12] = { 0.3,0.3,0.3,0.8, // starting color, transparent gray 0.0,0.0,0.0,1.0, // intermediate color, black 0.3,0.3,0.3,0.8 // ending color, transparent gray }; CGColorSpaceRef sp = CGColorSpaceCreateDeviceGray(); ...

Get Programming iOS 4 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.