Draw custom ellipse in winform

2019-09-16 18:09发布

In System.Drawing and System.Drawing.Drawing2D, I can only draw horizontal or vertical shape. Now i want to draw custom shape.

Given the coordinate of points A, B, C, D. I want to draw an ellipse like the blue one in the picture. enter image description here

2条回答
太酷不给撩
2楼-- · 2019-09-16 18:42

The example below is taken from MSDN:

private void RotateTransformAngle(PaintEventArgs e)
{
    // Set world transform of graphics object to translate.
    e.Graphics.TranslateTransform(100.0F, 0.0F);

    // Then to rotate, prepending rotation matrix.
    e.Graphics.RotateTransform(30.0F);

    // Draw rotated, translated ellipse to screen.
    e.Graphics.DrawEllipse(new Pen(Color.Blue, 3), 0, 0, 200, 80);
}
查看更多
闹够了就滚
3楼-- · 2019-09-16 19:06

The correct solution involves:

  • Calculating the center
  • using Graphics.TranslateTransform to move the center to the origin
  • Calculating the Size and the Location of the bounding Rectangle
  • using Graphics.RotateTransform to rotate the canvas
  • Drawing the ellipse with Graphics.DrawEllipse
  • Resetting the Graphcis object

This does take a little Math but will produce real and fine ellipses..

For fun you also may want to play with a cheap, fake solution: I uses the DrawClosedCurve method with a tension.

To test I added a TrackBar set with a Maximum of 100.

Values of around 80, i.e. Tensions of around 0.8f create pretty nice ellipsoids:

enter image description here

private void panel1_Paint(object sender, PaintEventArgs e)
{
    List<Point> points1 = new List<Point>()
    { new Point(300, 100), new Point(500, 300), new Point(400, 500), new Point(200, 300) };

    List<Point> points2 = new List<Point>() 
    { new Point(100, 100), new Point(500, 100), new Point(500, 400), new Point(100, 400) };

    e.Graphics.DrawClosedCurve(Pens.Red, points1.ToArray(), 
        (float)(trackBar1.Value / 100f), System.Drawing.Drawing2D.FillMode.Alternate);

    e.Graphics.DrawClosedCurve(Pens.Blue, points2.ToArray(), 
        (float)(trackBar1.Value / 100f), System.Drawing.Drawing2D.FillMode.Alternate);
}
查看更多
登录 后发表回答