GraphicsPath.AddArc如何使用startAngle和sweepAngle参数?

时间:2009-08-20 21:56:44

标签: c# graphics geometry gdi+ trigonometry

我正在尝试使用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));
    }

alt text

2 个答案:

答案 0 :(得分:4)

enter image description here我对GraphicsPath.AddArc的工作原理感到困惑。我找不到任何像样的图表,所以我画了一个。以防其他人遭受类似的痛苦! http://imgur.com/lNBewKZ

答案 1 :(得分:3)

GraphicsPath.AddArc完全按照你的要求去做 - 它是从椭圆中心投射的一条直线,与x轴顺时针成135度的精确角度。

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

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

width height 是椭圆的那些。

在示例代码中,尝试在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