Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 951
Vivian River Avatar asked Dec 09 '25 19:12

Vivian River


2 Answers

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.

like image 77
FMM Avatar answered Dec 12 '25 13:12

FMM


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.

like image 43
Peter O. Avatar answered Dec 12 '25 12:12

Peter O.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!