jam*_*lle 5 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));
}
Run Code Online (Sandbox Code Playgroud)
我对 GraphicsPath.AddArc 的工作原理感到困惑,并且找不到任何像样的图表,所以我画了一个。以防万一其他人也遭受类似的痛苦!https://i.stack.imgur.com/50HBn.jpg
GraphicsPath.AddArc 完全按照您的要求进行操作 - 它将弧线延伸到从椭圆中心投影的直线,与 x 轴顺时针精确地成 135 度角。
不幸的是,当您使用角度作为要绘制的饼图切片的直接比例时,这没有帮助。要找出需要与 AddArc 一起使用的角度 B,给定适用于圆的角度 A(以弧度为单位),请使用:
B = Math.Atan2(sin(A) * height / width, cos(A))
Run Code Online (Sandbox Code Playgroud)
其中宽度和高度是椭圆的宽度和高度。
在示例代码中,尝试在 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);
Run Code Online (Sandbox Code Playgroud)
结果应如下所示: alt text http://img216.imageshack.us/img216/1905/arcs.png
归档时间: |
|
查看次数: |
7710 次 |
最近记录: |