The sample code for this chapter demonstrates the technique of creating a simple layer and using that layer as part of a more complex graphic. The image that this code creates is illustrated in Figure 12.1. Figure 12.1. A Complex Pattern Composed from a Single Layer
The graphic in Figure 12.1 is drawn by repeating a single motif, a star in front of a circle. To create the graphic, the code draws the star and circle onto a layer. It then draws that layer repeatedly while modifying the rotation and scale of the drawing context to create the final image. The routine that makes use of the layer is given in Listing 12.2. Listing 12.2. Main Drawing Routine of the Star Pattern
The routine begins by calling the CreateStarLayer. This routine creates the CGLayer object and draws the circle and star graphic onto it. The routine accepts the context that will hold the final graphic as a parameter. After moving the origin to the center of the drawing area, the code enters a series of nested loops that adjust the transformation of the context. The meat of the routine is the call to CGContextDrawLayerAtPoint. Each call draws a single instance of our pattern motif in the context. After leaving the loops, the code releases the layer. The CreateStarLayer routine is given in Listing 12.3. Listing 12.3. Creating the Layer with the Star
This routine creates the layer and draws the star motif on it. The routine begins by setting up a few colors. Immediately after that, the code calls CGLayerCreateWithContext to create the layer that is the focus of this sample. The code uses CGLayerGetContext to get the CGContext for the layer and uses that context in a sequence of drawing commands to create the graphic on the layer. Note that the code does not own the layer's context and does not need to release it. After drawing on the layer, the code cleans up a few loose ends and returns the layer to the caller. This chapter introduced two of the offscreen graphics techniques built into Quartz 2D. Choosing the correct offscreen drawing mechanism can change depending on what that offscreen graphic will be used for. Applications that want to cache off graphics and draw them to a context quickly, or draw the same graphic many times, can store that graphic in a layer. If the application wants to access the pixels of the offscreen graphic, or export it into a file, then a bitmap graphics context is the proper choice. |