Search code examples
c#winformssystem.drawing

degree rotation on triangle without changing position using C# windows application?


private void panel1_Paint(object sender, PaintEventArgs e)
{
    Pen myPen = new Pen(Color.Blue, 1);
    Pen myPen2 = new Pen(Color.Red, 1);
    Point[] array = { new Point(639, 75), new Point(606, 124), new oint(664, 123) };
    matrix.TransformPoints(array);
    e.Graphics.Transform = matrix;

    e.Graphics.RotateTransform(ang, MatrixOrder.Append);

    myPen2.RotateTransform(ang, MatrixOrder.Append);

    e.Graphics.DrawPolygon(myPen2, array);
}

I'm using Visual Studio 2010. The above code should be for drawing a triangle in C#, but I can't rotate it without drawn triangle location. How can I achieve that?


Solution

  • This will do the rotation:

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        Pen myPen = new Pen(Color.Blue, 1);
        Pen myPen2 = new Pen(Color.Red, 1);
        Point[] array = { new Point(239, 75), new Point(206, 124), new Point(264, 123) };
    
        float x = array.Select(_ => _.X).Sum() / array.Length;
        float y = array.Select(_ => _.Y).Sum() / array.Length;
    
        e.Graphics.DrawPolygon(myPen, array);
    
        e.Graphics.TranslateTransform(x,y);
        e.Graphics.RotateTransform(ang);
        e.Graphics.TranslateTransform(-x, -y);
    
        e.Graphics.DrawPolygon(myPen2, array);
    }
    

    No need to rotate a simple Pen although for more adavanced pens this may well be called for..

    I have calculated the rotation center coordinates and then move the Graphics' origin there, rotate it and then move back. Then we can draw.

    To test you can use a trackbar:

    float ang = 0f;
    
    private void trackBar1_Scroll(object sender, EventArgs e)
    {
        ang = (float) trackBar1.Value;
        panel1.Invalidate();
    }