15.11. Scaling Shapes Drawn on Graphic Contexts

Problem

You want to scale shapes on your graphics context up and down dynamically.

Solution

Create an affine scale transformation using the CGAffineTransformMakeScale function.

Discussion

Recipe 15.10 explained what a transformation is, and how to apply it to shapes and graphics contexts. One of the transformations that you can apply is scaling. You can easily ask Core Graphics to scale a shape, such as a circle, to 100 times its original size.

To create an affine scale transformation, use the CGAffineTransformMakeScale function, which returns a transformation object of type CGAffineTransform. If you want to apply a scale transformation directly to a graphics context, use the CGContextScaleCTM procedure to scale the Current Transformation Matrix (CTM). For more information about CTM, see Recipe 15.10.

Scale transformation functions take two parameters: one to scale the x axis and the other to scale the y axis. Take another look at the rectangle in Figure 15-21. If we want to scale this rectangle to half its normal length and width, shown in Figure 15-21, we can simply scale the x and the y axis by 0.5 (half their original value), as shown here:

/* Scale the rectangle to half its size */
CGAffineTransform transform =
  CGAffineTransformMakeScale(0.5f, 0.5f);

/* Add the rectangle to the path */
CGPathAddRect(path,
              &transform,
              rectangle);

Figure 15-30 shows what we will see after applying the scale transformation to the code we wrote in Recipe 15.7 ...

Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.