0

I wanna make a rectangle rotate around its center. The rotation works perfectly but I can't figure out how to rotate it around its center. Can someone help me? Thanks! :) Here is my code:

    private void button1_Click(object sender, EventArgs e)
    {
        Paint += new PaintEventHandler(PaintRectangle);
        angle = 0;
        t = new Timer();
        t.Tick += new EventHandler(DrawRectangle);
        t.Interval = 1;
        t.Start();
    }

    private void DrawRectangle(object sender, EventArgs e)
    {
        angle++;
        Invalidate();
    }

    private void PaintRectangle(object sender, PaintEventArgs e)
    {
        Rectangle r = new Rectangle(0, 0, 100, 10);
        Graphics g = CreateGraphics();
        g.TranslateTransform(124, 150);
        g.RotateTransform(angle);
        g.DrawRectangle(Pens.White, r);
    }
DannyDSB
  • 145
  • 2
  • 12
  • Why would you assign the paint event handler again and again in the button click event? – Patrick Hofman Nov 24 '16 at 16:29
  • Because I wanna rotate it when that button is pressed. – DannyDSB Nov 24 '16 at 16:30
  • 3
    `Graphics g = CreateGraphics();` ouch! you should use the e.Graphics object. Here ansd __always__!! After the roation set the translate back __by the same amount__, then draw! The amount should be half the rectangle size! – TaW Nov 24 '16 at 16:35
  • Thanks, but it doesn't help me with my problem. – DannyDSB Nov 24 '16 at 16:37
  • @TaW, what's that different between `Graphics g = CreateGraphics();` and `Graphics g = e.Graphics;`? – DannyDSB Nov 24 '16 at 16:44
  • Only the one from the PaintArgs is valid; the other one produces shaky and (usually) non-persistent results. After making my suggested modifications your works works: `e.Graphics.TranslateTransform(50, 5); e.Graphics.RotateTransform(angle); e.Graphics.TranslateTransform(-50, -5); e.Graphics.DrawRectangle(Pens.Blue, r);` Make sure to turn on double-buffering for the form! Also note that a timer will never be faster than 15-25ms! – TaW Nov 24 '16 at 16:49
  • You may want to [read this](http://stackoverflow.com/questions/26450764/how-to-rotate-image-in-picture-box/26455088?s=6|1.4450#26455088) . The trick of the Translate/Rotate/Translate sequence is to move the origin(0,0) to the center of the rotation. Then rotate the port, then move it back. Then draw. – TaW Nov 24 '16 at 16:54
  • Thanks, @TaW :) You really helped me! – DannyDSB Nov 24 '16 at 16:55

1 Answers1

3

Translate all the vertices so that the center of the rectangle would be on (zero, zero). If the center of the rectangle is (x,y), you need to translate all vertices by (-x,-y). Then rotate by any angle and then translate vertices back by (x,y).

ir-tech
  • 298
  • 4
  • 16
Good Luck
  • 1,104
  • 5
  • 12