Search code examples
c#graphicsrectangles

Rotate Rectangle - C#


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

Solution

  • 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).