Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# RotateTransform - problems changing center

In my C# program I am using the RotateTransform Method do rotate the picture that I want to draw. This is already working, but I can't find out how I could change the centerpoint from where the picture rotates. At default it's the bottom left corner of my Picturebox, unfortunately I need to rotate around another point at (760, 480) px.

I've searched everywhere and only came across this CenterX property. CenterX msdn

Anyway, I don't seem to find this property with Visual Studio, so I guess I'm doing this wrong.

My current code looks like this:

*e.Graphics.RotateTransform(angle);
e.Graphics.DrawLine(Pens.Black, physicObj.lineStartingPoint, physicObj.lineEndingPoint);
e.Graphics.FillEllipse(new SolidBrush(Color.Red), new Rectangle(physicObj.leftCornerCircle, physicObj.circleSize));
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), new Rectangle(physicObj.leftCornerRectangle, physicObj.rectangleSize));*

This part is working fine but uses a wrong center point to rotate around. I have tried to use

e.Graphics.RotateTransform.CenterX = ... ;

But there seems to be no CenterX accessible within e.Graphics.RotateTransform. Visual Studio displays a red line beneath RotateTransform saying it is a method, which is not valid in the given context. I don't know the way to set this property and I haven't found any coding examples doing so, and based on the info that Microsoft gives (in the link) I thought this was the way to do it.

Hopefully someone can explain what I need to do to change this center point. Thank you!

like image 296
ItsShowtime Avatar asked May 06 '26 17:05

ItsShowtime


1 Answers

It's quite simple:
1. translate to the center
2. rotate
3. translate back

float centerX = 760;
float centerY = 480;
e.Graphics.TranslateTransform(-centerX, -centerY);
e.Graphics.RotateTransform(angle);
e.Graphics.TranslateTransform(centerX, centerY);

Essentially, you create 3 matrices and multiply them to achieve the result - a single transformation matrix, the basics of 2D and 3D transformations.


P.S. you can create an extension method for convenience:

public static class GraphicsExtensions
{
  public static void TranslateTransform(this Graphics g, float x, float y, float angle)
  {
    g.TranslateTransform(-x, -y);
    g.RotateTransform(angle);
    g.TranslateTransform(x, y);
  }
}
like image 183
Serge Semenov Avatar answered May 09 '26 05:05

Serge Semenov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!