NSAffineTransform provides an interface for defining and applying affine transforms to various parts of the graphics system, such as view coordinate systems, individual Bezier paths or NSPoints. An affine transform is a type of mapping between coordinate systems in which a shape's parallel lines are preserved, but not necessarily the length of line segments or the angles between lines. Out-of-the-box, NSAffineTransform is capable of rotating, translating, and scaling.
To create an affine transform, use the transform convenience constructor. The following example shows how you can create an affine transform object and make a rotation transformation:
NSAffineTransform * at = [NSAffineTransform transform]; [at rotateByDegrees:77];
To transform a Bezier path using this affine transform object, invoke transformBezierPath:
NSBezierPath *newPath = [at transformBezierPath:bp];
This method takes the Bezier path to transform as a parameter and returns a new Bezier path that is the transformation of the original. Using a method of NSBezierPath, you can transform a path directly without having a new object returned. The method is transformUsingAffineTransform:, and is used in the following way:
Here is how you transform an NSPoint structure:
at = [NSAffineTransform transform]; [at translateXBy:100 yBy:50]; NSPoint point = NSMakePoint( 0, 0 ); NSPoint newPoint = [at transformPoint:point];
To transform an NSSize, do the following:
at = [NSAffineTransform transform]; [at scaleXBy:0.5 yBy:1.5]; NSSize size = NSMakeSize( 100, 100 ); NSSize newSize = [at transforSize:size];
The beginning of this chapter discussed graphics contexts and how they control drawing destination properties. One of these properties is a global transformation matrix that is the concatenation of all scaling, translation, and rotation applied by windows and views between and including the screen and the current view.
NSAffineTransform implements two methods that let you alter the graphic context's transformation matrix: set and concat. The first, set, lets you replace the current context's transformation matrix. This is usually not a good idea, since the replacement destroys all information about transformations between windows and views. The other, concat, appends the transformation represented by the receiver to the current context's transformation. All drawing operations subsequent to the invocation of either method have the new transformation applied. Be sure to save the current context before using these methods, and restore that context whenever you complete a drawing operation.