Rotating Graphics

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:

Category: Useful .Net classes | Tags: ,


Leave a Reply