Let’s throw some paint on the canvas. Like any good artist, Quartz 2D likes to paintoutlines before it fills in a scene. These outlines are calledpaths. The following lines ofcode create a rectangular path (the lines are numbered on the right for clarity).
CGContextBeginPath(context); (1)
CGContextSetRGBFillColor(context, 0,1,0,1); (2)
CGContextAddRect(context, CGRectMake(0,0,100,200)); (3)
CGContextClosePath(context); (4)
As before, the API functions begin with the lettersCG. Most calls require the graphicscontext, which we went through great pains to create.CGContextBeginPath, on line 1,starts a fresh, new path in Quartz 2D. The Quartz 2D engine is like an artist with just onepair of hands. At any time, only one path is being created.
CGContextSetRGBFillColor, on line 2, specifies the color we would like to use in ourpath. Colors in Quartz 2D are specified in three unit values—a floating-point numberbetween 0 and 1—for each of red, green, and blue. A value of 0 means to use no colorfor the given color component, 0.5 means to use 50% of that color, and 1.0 means touse 100% of the color. A fourth unit value represents the opacity, where 0 means thegraphic is invisible, 0.5 means make the graphic 50% transparent, and 1 means thegraphic is completely opaque. Quartz has numerous, powerful ways to combine thesecolors for interesting effects. For now, we’ll use the default, which just adds thecomponents together to create a single green, completely opaque color:
(0 x red) + (1.0 x green) + (0.0 x blue) at an opacity of 1.0
CGContextAddRect, on line 3, adds a single rectangle to the current path. We describeour rectangle using theCGRectMakemacro. The macro is passed an origin (0,0), a width(100), and a height (200).
CGContextClosePath, on line 4, tells Quartz 2D that we’re finished with the current path,and ready to paint with it on the canvas. The following call tells Quartz to take thecurrent path, fill it in with the current color, and add it to the canvas. The first argumentis the context. The second argument is a drawing mode, one of several available.
CGContextDrawPath(context,kCGPathFill);
Finally, being good citizens, we restore the state of the canvas with a single call:
CGContextRestoreGState(context);