Home > Articles > Programming > General Programming/Other Languages

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

Drawing into Contexts

Many Quartz functions depend on referencing a context that you can draw into. For example, consider the function calls in Listing 1-5. These set a 4-pixel-wide line width, set a gray color, and then stroke an ellipse within a rectangular container. Each function call requires a context parameter, which must be a valid CGContextRef. You can build this context yourself (as in Listing 1-4) or retrieve one from UIKit, which is explored in the next section.

Listing 1-5 Drawing an Ellipse

// Set the line width
CGContextSetLineWidth(context, 4);

// Set the line color
CGContextSetStrokeColorWithColor(context,
    [UIColor grayColor].CGColor);

// Draw an ellipse
CGContextStrokeEllipseInRect(context, rect);

The code in Listing 1-5 naturally lives where Listing 1-4 says, Perform drawing here. At this point in Listing 1-4, you have fully created a bitmap context reference, and you can use that reference with these drawing requests.

By the end of Listing 1-4, you’ve created an image and manually released the context. Figure 1-5 shows the output created by merging Listing 1-5 into Listing 1-4. The image you produce is a gray ellipse, stroked with a 4-pixel-wide line. Figure 1-5 shows that image displayed in a UIImageView instance.

Figure 1-5

Figure 1-5 Core Graphics functions require a context to draw this ellipse.

This entire process is performed outside the auspices of UIKit. The only UIKit call is imageWithCGImage:, which converts the newly created CGImageRef to a UIImage instance.

  • + Share This
  • 🔖 Save To Your Account