Day 24: Drawing: NSAffineTransform, part 1
Today we’ll continue our little drawing series with a short introdroduction to NSAffineTransform. This class is useful for either translating coordinates to a different coordinate space or - and this is more important - changing all future drawing for the current graphics context in a certain way.
By default, the 0,0-coordinate lies in the bottom left but you can move the origin around with NSAffineTransform. Usually when drawing stuff, a rectangle of 10 by 10 will when you draw actually be 10 by 10 pixels. But not necessarily; with NSAffineTransform you can scale everything on the X or Y axis by certain amount to either scale things up or make things look stretched. It’s also possible to rotate the coordinate system around the origin. Rotating by 45 degrees will result in a straight line to be drawn at a 45 degrees angle.
This gives us three basic operations; moving, scaling and rotating. (You can skew as well if you want to dive into matrix math but we won’t do that today) These can be chained together to produce interesting results. You can build your transform easily and that part is quite properly documented. To aply your transform to the current graphics context, you call concat. To undo it, either wrap the concat and your drawing code in an NSGraphicsContext save/restore (as explained a few days ago), or invert and then concat again. The latter is a cheaper operation than restoring a graphics context so when possible, do that.
Tomorrow I’ll give a few examples of transforming graphics contexts.