Rotating Ellipses

On a recent problem I had to draw lines of ellipses across a background image, some at 45 degrees.

The Graphics.FillEllipse method draws an ellipse at the specified x,y. While researching into how to rotate these using the RotateAt method I ended up not only rotating each ellipse but also the whole line of ellipses ended up changing its direction. The reason being that the rotate causes the whole graphics object to be rotated so the x and y changes. Also the rotation occurs around a specified point which defaults to 0,0 (or the upper left corner of the container).

To rotate an individual ellipse I ended up doing the following:


Matrix matrix = new Matrix();
Graphics g;

int x = 10; //Where you want to draw the ellipse
int y = 10; //Where you want to draw the ellipse

//Find the centre of the ellipse to be drawn
float ellipseCenterX = X + (ellipseWidth / 2);
float ellipseCenterY = y + (ellipseHeight / 2);

//Rotate the graphics object the required amount around this point
matrix.RotateAt(45f, new PointF(ellipseCenterX, ellipseCenterY));
g.Transform = matrix;

//Draw the rotated ellipse
Rectangle r = new Rectangle(x, y, ellipseWidth, ellipseHeight;
g.FillEllipse(Brushes.Red, r);

//Rotate back to normal around the same point</pre>
matrix.RotateAt(-45, new PointF(ellipseCenterX, ellipseCenterY));
g.Transform = matrix;

And there is the rotated ellipse, by putting the transformation back to the normal rotation you can now move to another x,y using the normal co-ordinates and draw another ellipse.

Advertisements

One thought on “Rotating Ellipses

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s