System.Drawing.Graphics

2019-05-17 10:50发布

问题:

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…….

回答1:

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);


回答2:

//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);
}