Can the translate and rotate state of a graphics be read anywhere?
Is there a way to set the values to zero without knowing the current state?
I have been reversing the settings after each call:
g.rotate(.2)
g.Translate(100,100)
' ...drawing operation
g.Translate(-100,-100)
g.rotate(-.2)
Thanks
Rotate/translate are lossy operations. Once you do them, the new values are the new zero.
But you should be able to use Graphics.SaveState and Graphics.RestoreState instead of doing the reverse operations.
Thanks for that. It’s a time saver.
Under the hood, here’s what is going on.
The graphics context maintains a certain amount of state – for example, what font to use when drawing text, what width of line to draw, etc. – and that state affects all drawing that is done in that moment. When you change the line width, all lines drawn afterwards will use the new line width value.
One of the pieces of state that Graphics maintains is called the transformation matrix. This is a 3 x 3 matrix of floating point values that transform coordinates from user space (how your code thinks about the coordinates) to device space (the coordinates in the drawing context after they are modified by the matrix). The math involved isn’t terrifically complex but you can safely ignore it in Xojo.
Unlike some graphics frameworks, you don’t have direct access to the values in the transformation matrix. Instead, the matrix vales are modified by the rotate, translate, and scale methods of the Graphics object. Each of those methods accepts a value from your code (for example, the degree of rotation) and applies that value to the transformation matrix. All drawing done after the transformation matrix is changed will be affected by it.
Because transformation matrices use math concepts such as sine and square roots, it isn’t advisable to try to undo transformations by reversing the operations (for example, rotating by 9 degrees and later rotating by -9 degrees). The math involved in calculating sine and square roots is not 100% reversible and will introduce small errors into the matrix values that increase the more you reverse operations.
Instead, it is best practice to use Graphics.SaveState and Graphics.RestoreState to save the entire graphics state for later restoration. This includes all of the typical Graphics properties as well as the hidden values of the transformation matrix, guaranteeing that you will be able to return to the exact transformation that was in place prior to any subsequent transformations.
If you are curious about the underlying theory of transformation matrices, there is an excellent Wikipedia article with interactive demonstrations: