Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

winforms - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...