Search code examples
c#algorithmgraphicsdundas

Calculate points to create a curve or spline to draw an ellipse


I am working with Dundas maps and need to overlay the map with bubbles depicting some data. I want to add shapes to the map in order to achieve this. I can add a triangle (or any straight-line-polygon) like this:

public static void AddShape(this MapControl map, List<MapPoint> points, Color color, string name)
{
    if (points[0].X != points[points.Count - 1].X && points[0].Y != points[points.Count - 1].Y)
        points.Add(points[0]);
    var shape = new Shape
    {
        Name = name,
        BorderColor = color,
        BorderStyle = MapDashStyle.Solid,
        BorderWidth = 1,
        Color = Color.FromArgb((int)(255 * (0.3)), color)
    };
    var segments = new[] {new ShapeSegment {Type = SegmentType.Polygon, Length = points.Count}};
    shape.AddSegments(points.ToArray(), segments);
    map.Shapes.Add(shape);
}

public static void AddBermudaTriangle(this MapControl map)
{
    var points = new List<MapPoint>
                     {
                         new MapPoint(-80.15, 26.0667),
                         new MapPoint(-64.75, 32.333),
                         new MapPoint(-66.07, 18.41)
                     };
    map.AddShape(points, Color.Red, "Bermuda Triangle");
}

Bermuda Triangle

You can see that the Bermuda Triangle overlays the map in red. Now I want to calculate a set of points to pass to my AddShape method that would draw an elipse or circle. I just need a simple algorithm for calculating the x and y coordinates of a given number of points. Perhaps starting with a given point that would represent the centre of the circle. For example:

public static void AddCircle(this MapControl map, Point centre, double radius, string name)
{
    var points = new List<MapPoint>();
    const int n = 360;
    for(var i = 0; i < n; i++)
    {
        //calculate x & y using n, radius and centre
        double x = 0;
        double y = 0;
        points.Add(new MapPoint(x, y));
    }
    map.AddShape(points, Color.Red, name);
}

I know that the x,y calculation is simple trigonometry but I'm suffering a brain freeze. Help!

EDIT (Solved using tur!ng's code):

public static void AddCircle(this MapControl map, Color color, MapPoint centre, double radius, string name)
{
    var points = new List<MapPoint>();
    const int n = 360;
    for(var i = 0; i < n; i++)
    {
        var x = (radius * Math.Cos(i * Math.PI / 180)) + centre.X;
        var y = (radius * Math.Sin(i * Math.PI / 180)) + centre.Y;
        points.Add(new MapPoint(x, y));
    }
    map.AddShape(points, color, name);
}

alt text

The blue circle (over Greenwich) is distorted because of the map projection over a Robinson grid.


Solution

  •   double x = centre.x + radius*Math.cos(2*Math.PI/360 * i);
      double y = centre.y + radius*Math.sin(2*Math.PI/360 * i);
    

    for a circle.