How to draw a section of a circle using System.Windows.Shapes.Path?

那年仲夏 提交于 2019-12-12 15:04:11

问题


I have a Silverlight application where I draw lines on a picture by instantiating an instance of System.Windows.Shapes.Line and then adding it to MainCanvas.Children.

I would like to similarly add some circle segments. If I understand correctly, I will want to use the Path class.

I have the following requirement. I have (x,y) coordinates for the center of the circle. I have the radius r. I need to draw an arc that is a subset of the circle with center (x,y) and radius r. I have two angles a1 and a2 between which I need to draw the arc.

How can I do this?


回答1:


You'll need to build a string that identifies the path using an arc, which is supported by WPF. The string follows the syntax on this page.

However, the parameters must first be converted to the arc format given in the syntax, since the values used are a little different:

First, convert the angles a1 and a2 to radians, if they aren't already.

a1=a1*Math.PI/180;
a2=a2*Math.PI/180;

Then, calculate the start and end point of the arc:

double startX = centerX+Math.Cos(a1)*r;
double startY = centerY+Math.Sin(a1)*r;
double endX = centerX+Math.Cos(a2)*r;
double endY = centerY+Math.Sin(a2)*r;

Then, calculate whether the difference between the angles is PI or greater, then whether a1 is less than a2.

bool largeArc = Math.Abs(a2-a1)>=Math.PI;
bool sweep = (a1<a2);

Finally, construct the path.

string path=String.Format(System.Globalization.CultureInfo.InvariantCulture,
     "M {0},{1} A {2},{3} 0 {4} {5} {6},{7}",startX,startY,r,r,
     largeArc ? 1 : 0, sweep ? 1 : 0,endX,endY);

That's the path string, not the Path object, that you'll use in defining the path.




回答2:


You'll want to use the PathGeometry syntax.

Consider something like:

<Path Stroke="Black" Fill="Transparent">
  <Path.Data>
    <PathGeometry Figures="M 0,0 A 15,15 90 0 1 15,15" />
  </Path.Data>
</Path>

This will draw a 90-degree circular arc starting at 0,0, ending at 15,15 in a clockwise direction.



来源:https://stackoverflow.com/questions/8000084/how-to-draw-a-section-of-a-circle-using-system-windows-shapes-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!