Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
This chapter is from the book

Clipping

Clipping enables you to exclude any painting operations that fall outside a path within your context. To clip, add a path to your context and then call the CGContextClip() clipping function. Figure 1-12 shows an example, where colored circles drawn to a context are clipped within the letters of the word Hello.

Figure 1-12

Figure 1-12 Randomly colored circles are clipped to the boundaries of the word Hello.

Listing 1-11 demonstrates the steps involved in clipping:

  1. Save the graphic state. This enables you to restore the state to a preclipped version at a later time. If you won’t need to return to an unclipped state, skip this step.
  2. Add a path to the context and clip to it using CGContextClip(). Adding a path temporarily stores it in the graphics context. When stored, you create a mask by clipping. This blocks out the parts of the context you don’t want to paint to. This example uses a UIBezierPath instance, which is not compatible with the CGContextClip() function. Retrieve the CGPathRef from the Bezier path’s CGPath property and pass that instead.
  3. When clipped, perform any standard drawing operations. Material drawn outside the bounds of the clipping path is automatically discarded on your behalf.
  4. To finish, restore the graphic state. This allows you to resume normal drawing without any further clipping, returning the context to the state before you began clipped operations.

This process amounts to saving, clipping, drawing, and restoring. (Say it out loud.) Chapter 6 introduces ways to use Objective-C blocks to clip and draw within saved-and-restored graphics states rather than managing those states through explicit calls.

Listing 1-11 Drawing Using Clipping

// Save the state
CGContextSaveGState(context);

// Add the path and clip
CGContextAddPath(context, path.CGPath);
CGContextClip(context);

// Perform clipped drawing here

// Restore the state
CGContextRestoreGState(context);

// Drawing done here is not clipped
  • + Share This
  • 🔖 Save To Your Account