Pregunta

I'm working on a method to programatically draw equilateral polygon shapes in C#, WPF. But I have been stuck and I can't solve calculating the angles. Where is the problem? How should I correct this? I have given the public int, R(radius) a value of 100.

private Path EquilateralPolygon(int sides)
    {
        //Centering
        Point center = new Point(canvasSize.Width / 2, canvasSize.Height / 2);

        PathFigure myPathFigure = new PathFigure();

        int alfa = 360 / sides;
        int[] angles = new int[6];
        for (int i = 0; i < sides; i++)
            angles[i] = 360 - alfa * i;

        MessageBox.Show(angles.Sum().ToString());

        Point A = new Point(center.X, center.Y - R);

        myPathFigure.StartPoint = A;
        PolyLineSegment myLineSegment = new PolyLineSegment();
        for (int i = 1; i < sides; i++)
        {
            myLineSegment.Points.Add(new Point(center.X + Math.Cos(angles[i]) * R, center.Y + Math.Sin(angles[i]) * R));
        }

        myLineSegment.Points.Add(A);

        PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
        myPathSegmentCollection.Add(myLineSegment);

        myPathFigure.Segments = myPathSegmentCollection;

        PathFigureCollection myPathFigureCollection = new PathFigureCollection();
        myPathFigureCollection.Add(myPathFigure);

        PathGeometry myPathGeometry = new PathGeometry();
        myPathGeometry.Figures = myPathFigureCollection;

        Path myPath = new Path();
        myPath.Stroke = Brushes.Red;
        myPath.StrokeThickness = 1;
        myPath.Data = myPathGeometry;

        return myPath;

    }
¿Fue útil?

Solución

You've posted a lot of code and were not specific about how it's not working, so there may be more than one issue with your code. However, one big issue is that the Math.Cos (and related trig methods) take the angle in the form of radians, not degrees as you have them.

Parameters

d

Type: System.Double An angle, measured in radians.

You will need to convert them to radians. To convert, multiply by π (available via Math.PI) then divide by 180 degrees.

myLineSegment.Points.Add(
    new Point(center.X + Math.Cos(angles[i] * Math.PI / 180.0) * R, 
    center.Y + Math.Sin(angles[i] * Math.PI / 180) * R));

EDIT: In addition to the radians/degrees issue, I can see you may be experiencing integer truncation, both in the use of your angles array and your calculation of alfa. I would suggest you try changing your use of integers to double so that your code works fine with fractions of a degree.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top