Archive for March 2009


Rotating Graphics

March 29th, 2009 — 10:12 am

This is a fairly simple issue, but I had to rotate a drawn shape recently.

Initial searches led me to the TranslateTransform method, but I learned there is a simpler way to achieve this, using the RotateAt method of the Matrix class:

Graphics g = this.CreateGraphics(); //get a graphics object for the form
g.DrawRectangle(new Pen(Color.Black), 50, 50, 100, 100); //normal drawingMatrix oldMatrix = g.Transform; //save the old Matrix objectMatrix myMatrix = new Matrix(); //create a new Matrix object

myMatrix.RotateAt(15, new PointF(200.0f, 200.0f)); //rotate the matrix in relation to a specific point (200, 200) by 15 degrees
g.Transform = myMatrix; //assign the new (rotated) matrix to the graphics object
g.DrawRectangle(new Pen(Color.Black), 100, 100, 100, 100); //perform the drawing

g.Transform = oldMatrix; //restore the original matrix

The result:

Comment » | Useful .Net classes