There are three steps you need to paint to a transparency layer:
Call the function CGContextBeginTransparencyLayer.
Draw the items you want to composite in the transparency layer.
Call the function CGContextEndTransparencyLayer.
The three rectangles in Figure 9-3 are painted to a transparency layer. Quartz renders the shadow as if the rectangles are a single unit.
The function in Listing 9-1 shows how to use a transparency layer to generate the rectangles in Figure 9-3. A detailed explanation for each numbered line of code follows the listing.
Listing 9-1 A function that paints to a transparency layer
void MyDrawTransparencyLayer (CGContext myContext, // 1 |
float wd, |
float ht) |
{ |
CGSize myShadowOffset = CGSizeMake (10, -20);// 2 |
CGContextSetShadow (myContext, myShadowOffset, 10); // 3 |
CGContextBeginTransparencyLayer (myContext, NULL);// 4 |
// Your drawing code here// 5 |
CGContextSetRGBFillColor (myContext, 0, 1, 0, 1); |
CGContextFillRect (myContext, CGRectMake (wd/3+ 50,ht/2 ,wd/4,ht/4)); |
CGContextSetRGBFillColor (myContext, 0, 0, 1, 1); |
CGContextFillRect (myContext, CGRectMake (wd/3-50,ht/2-100,wd/4,ht/4)); |
CGContextSetRGBFillColor (myContext, 1, 0, 0, 1); |
CGContextFillRect (myContext, CGRectMake (wd/3,ht/2-50,wd/4,ht/4)); |
CGContextEndTransparencyLayer (myContext);// 6 |
} |
Here’s what the code does:
Takes three parameters—a graphics context and a width and height to use when constructing the rectangles.
Sets up a CGSize data structure that contains the x and y offset values for the shadow. This shadow will be offset by 10 units in the horizontal direction and –20 units in the vertical direction.
Sets the shadow, specifying a value of 10 as the blur value. (A value of 0 specifies a hard edge shadow with no blur.)
Signals the start of the transparency layer. From this point on, drawing occurs to this layer.
The next six lines of code set fill colors and fill the three rectangles shown in Figure 9-3. You replace these lines with your own drawing code.
Signals the end of the transparency layer and signals that Quartz should composite the result into the context.
Last updated: 2007-12-11