Graphics Reference
In-Depth Information
Listing 5.1
Rotating a Layer by 45 Degrees Using
affineTransform
@interface
ViewController ()
@property
(
nonatomic
,
weak
)
IBOutlet
UIView
*layerView;
@end
@implementation
ViewController
- (
void
)viewDidLoad
{
[
super
viewDidLoad
];
//rotate the layer 45 degrees
CGAffineTransform
transform = CGAffineTransformMakeRotation(
M_PI_4
);
self
.
layerView
.
layer
.affineTransform = transform;
}
@end
Note that the value we've used for the angle is a constant called
M_PI_4
, not the number
45 as you might have expected. The transform functions on iOS use radians rather than
degrees for all angular units. Radians are usually specified using multiples of the
mathematical constant π (pi). π radians equates to 180 degrees, so π divided by 4 is
equivalent to 45 degrees.
The C math library (which is automatically included in every iOS project) conveniently
provides constants for common multiples of π, and
M_PI_4
is the constant representing π
divided by 4. If you struggle to think in terms of radians, you can use these macros to
convert to and from degrees:
#define
RADIANS_TO_DEGREES
(x) ((x)/
M_PI
*
180.0
)
#define
DEGREES_TO_RADIANS
(x) ((x)/
180.0
*
M_PI
)
Combining Transforms
Core Graphics also provides a second set of functions that can be used to apply a further
transform on top of an existing one. This is useful if you want to create a single transform
matrix that both scales
and
rotates a layer, for example. These functions are as follows:
CGAffineTransformRotate(
CGAffineTransform
t,
CGFloat
angle)
CGAffineTransformScale(
CGAffineTransform
t,
CGFloat
sx,
CGFloat
sy)
CGAffineTransformTranslate(
CGAffineTransform
t,
CGFloat
tx,
CGFloat
ty)