在winform中绘制自定义椭圆

Draw custom ellipse in winform

System.DrawingSystem.Drawing.Drawing2D中,我只能绘制水平或垂直形状。现在我想绘制自定义形状。

给定A、B、C、D点的坐标,我想画一个像图中蓝色的椭圆。

下面的例子来自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);
}

正确的解决方案包括:

  • 计算中心
  • 使用Graphics.TranslateTransform将中心移动到原点
  • 计算边界的SizeLocationRectangle
  • 使用Graphics.RotateTransform旋转canvas
  • Graphics.DrawEllipse画椭圆
  • 重置 Graphcis 对象

这确实需要一些时间 Math 但会产生真实而精细的椭圆..

为了好玩,您可能还想玩一个廉价的假解决方案:我使用了 DrawClosedCurve 方法,但很紧张。

为了测试,我添加了一个 TrackBar 集,其中 Maximum100

大约 80 的值,即大约 0.8fTensions 创建非常好的椭圆体:

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