With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

17.12. 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 17.11 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 17.11.

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 17-27. If we want to scale this rectangle to half its normal length and width, shown in Figure 17-27, 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 */