5

我正在尝试使用 System.Drawing.Drawing2D.GraphicsPath.AddArc 绘制从 0 度开始并扫到 135 度的椭圆弧。

我遇到的问题是,对于椭圆,绘制的弧与我期望的不匹配。

例如,以下代码生成下面的图像。绿色圆圈是我希望弧的端点使用椭圆沿点的公式的地方。我的公式适用于圆形,但不适用于椭圆。

这与极坐标与笛卡尔坐标有关吗?

    private PointF GetPointOnEllipse(RectangleF bounds, float angleInDegrees)
    {
        float a = bounds.Width / 2.0F;
        float b = bounds.Height / 2.0F;

        float angleInRadians = (float)(Math.PI * angleInDegrees / 180.0F);

        float x = (float)(( bounds.X + a ) + a * Math.Cos(angleInRadians));
        float y = (float)(( bounds.Y + b ) + b * Math.Sin(angleInRadians));

        return new PointF(x, y);
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Rectangle circleBounds = new Rectangle(250, 100, 500, 500);
        e.Graphics.DrawRectangle(Pens.Red, circleBounds);

        System.Drawing.Drawing2D.GraphicsPath circularPath = new System.Drawing.Drawing2D.GraphicsPath();
        circularPath.AddArc(circleBounds, 0.0F, 135.0F);
        e.Graphics.DrawPath(Pens.Red, circularPath);

        PointF circlePoint = GetPointOnEllipse(circleBounds, 135.0F);
        e.Graphics.DrawEllipse(Pens.Green, new RectangleF(circlePoint.X - 5, circlePoint.Y - 5, 10, 10));

        Rectangle ellipseBounds = new Rectangle(50, 100, 900, 500);
        e.Graphics.DrawRectangle(Pens.Blue, ellipseBounds);

        System.Drawing.Drawing2D.GraphicsPath ellipticalPath = new System.Drawing.Drawing2D.GraphicsPath();
        ellipticalPath.AddArc(ellipseBounds, 0.0F, 135.0F);
        e.Graphics.DrawPath(Pens.Blue, ellipticalPath);

        PointF ellipsePoint = GetPointOnEllipse(ellipseBounds, 135.0F);
        e.Graphics.DrawEllipse(Pens.Green, new RectangleF(ellipsePoint.X - 5, ellipsePoint.Y - 5, 10, 10));
    }

替代文字

4

2 回答 2

5

在此处输入图像描述我对 GraphicsPath.AddArc 的工作方式感到困惑,我找不到任何像样的图表,所以我画了一张。以防万一其他人也遭受同样的痛苦!http://imgur.com/lNBewKZ

于 2016-11-02T14:00:44.787 回答
2

GraphicsPath.AddArc 完全按照您的要求执行 - 它是从椭圆中心突出的一条直线,与 x 轴顺时针方向的精确角度为 135 度。

不幸的是,当您将角度用作要绘制的饼图切片的直接比例时,这无济于事。要找出您需要与 AddArc 一起使用的角度 B,给定在圆上工作的角度 A,以弧度表示,请使用:

B = Math.Atan2(sin(A) * height / width, cos(A))

其中宽度高度是椭圆的宽度和高度。

在您的示例代码中,尝试在 Form1_Paint 的末尾添加以下内容:

ellipticalPath = new System.Drawing.Drawing2D.GraphicsPath();
ellipticalPath.AddArc(
    ellipseBounds,
    0.0F,
    (float) (180.0 / Math.PI * Math.Atan2(
        Math.Sin(135.0 * Math.PI / 180.0) * ellipseBounds.Height / ellipseBounds.Width,
        Math.Cos(135.0 * Math.PI / 180.0))));
e.Graphics.DrawPath(Pens.Black, ellipticalPath);

结果应如下所示: alt text http://img216.imageshack.us/img216/1905/arcs.png

于 2009-08-20T22:25:33.430 回答