Graphics Reference
In-Depth Information
Creating a
CGAffineTransform
A full explanation of matrix mathematics is beyond the scope of this topic, and if you are
not already familiar with matrices, the idea of a transform matrix can seem quite daunting.
Fortunately, Core Graphics provides a number of built-in functions for building up arbitrary
transforms out of simple ones without requiring the developer to do any math. The
following functions each create a new
CGAffineTransform
matrix from scratch:
CGAffineTransformMakeRotation(
CGFloat
angle)
CGAffineTransformMakeScale(
CGFloat
sx,
CGFloat
sy)
CGAffineTransformMakeTranslation(
CGFloat
tx,
CGFloat
ty)
The rotation and scale transforms are fairly self-explanatory—they rotate and scale a vector
respectively. A
translation
transform just adds the specified x and y values to the vector—
so if the vector represents a point, it moves the point.
Let's demonstrate the effect of these functions with a simple project. We'll start with an
ordinary view and apply a 45-degree rotation transform (see Figure 5.3).
Figure 5.3
A view rotated 45 degrees using an affine transform
A
UIView
can be transformed by setting its
transform
property, but as with all layout
properties, the
UIView
transform
is really just a wrapper around an equivalent
CALayer
feature.
CALayer
also has a
transform
property, but its type is
CATransform3D
, not
CGAffineTransform
. We come back to that later in the chapter, but for now it's not
what we're looking for. The
CALayer
equivalent to the
UIView
transform
property is
called
affineTransform
. Listing 5.1 shows the code for rotating a layer by 45 degrees
in the clockwise direction using the
affineTransform
property.