1
votes

I'm using GDI+ to try to draw a rectangle on the screen and rotate it 45 degrees.
Here's the code I'm using

Pen RedPen(Color(255, 255, 0, 0), 4);

HDC screenDC = GetDC(NULL);
Graphics graphics(screenDC);

graphics.RotateTransform(45);
graphics.DrawRectangle(&RedPen, 150, 150, 50, 50);

The rectangle rotates, but it's position moves in a circle the more it rotates.
I'm pretty sure this is because I'm rotating the center of the screen, instead of the center of the rectangle?
So how would I rotate it around the center of the rectangle?

1

1 Answers

1
votes

The problem is that it's not rotating around the center of the Rectangle as you noticed. So you need to translate the object after it's rotated.

        e->Graphics->RotateTransform(degrees);
        e->Graphics->TranslateTransform(posX, posY, MatrixOrder::Append);
        e->Graphics->DrawRectangle(gcnew Pen( Color::Blue,3.0f ),  -width / 2, -height / 2, width, height);

degrees is the amount you want to rotate your rectangle. posX and posY are the position where you want to draw it in screen.

Also you need to make sure you pass MatrixOrder::Append otherwise the order of the Transform might be changed and that will apply the Translation before rotating (giving you a similar effect to what you are seeing)