3

I have one problem relating to rotate ellipse by given Center, Suppose I have one ellipse and what should be is to rotate that ellipse by point given by user and ellipse should be rotate around that given point. I have tried

g.RotateTransform(…)
g.TranslateTransform(…)

Code:

Graphics g = this.GetGraphics(); 
g.RotateTransform((float)degreeArg); //degree to rotate object 
g.DrawEllipse(Pens.Red, 300, 300, 100, 200);

this works fine but how can we give our out center to rotate ellipse....

How could it be possible please any buddy can suggest…… Thanks…….

mdm
  • 12,480
  • 5
  • 34
  • 53
Pritesh
  • 3,208
  • 9
  • 51
  • 70
  • 1
    Show us the code you have so far. – mdm Mar 14 '11 at 11:59
  • Graphics g = this.GetGraphics(); g.RotateTransform((float)degreeArg); //degree to rotate object g.DrawEllipse(Pens.Red, 300, 300, 100, 200); this works fine but how can we give our out center to rotate ellipse.... – Pritesh Mar 14 '11 at 12:12
  • 1
    you should **edit** your question to include the code, not post it as a comment. It's been done for you this time. – ChrisF Mar 14 '11 at 12:39
  • Thanks i will bear in mind your comment for next time..... – Pritesh Mar 14 '11 at 12:48

2 Answers2

4

RotateTransform always rotates about the origin. So you need to first translate your centre of rotation to the origin, then rotate, then translate it back.

Something like this:

Graphics g = this.GetGraphics(); 
g.TranslateTransform(300,300);
g.RotateTransform((float)degreeArg); //degree to rotate object 
g.TranslateTransform(-300,-300);
g.DrawEllipse(Pens.Red, 300, 300, 100, 200);
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
  • Now i have found the solution and the solution is //center of the rotation PointF center = new PointF(...); //angle in degrees float angle = 45.0f; //use a rotation matrix using (Matrix rotate = new Matrix()) { //used to restore g.Transform previous state GraphicsContainer container = g.BeginContainer(); //create the rotation matrix rotate.RotateAt(angle, center); //add it to g.Transform g.Transform = rotate; //draw what you want ... //restore g.Transform state g.EndContainer(container); } – Pritesh Mar 14 '11 at 13:02
  • @pritesh, I had the order of translate transforms backwards - see my edit – Blorgbeard Mar 14 '11 at 13:08
3
//center of the rotation
PointF center = new PointF(...);
//angle in degrees
float angle = 45.0f;
//use a rotation matrix
using (Matrix rotate = new Matrix())
{
    //used to restore g.Transform previous state
    GraphicsContainer container = g.BeginContainer();

    //create the rotation matrix
    rotate.RotateAt(angle, center);
    //add it to g.Transform
    g.Transform = rotate;

    //draw what you want
    ...

    //restore g.Transform state
    g.EndContainer(container);
}
Pritesh
  • 3,208
  • 9
  • 51
  • 70