1 Pluspunkt 0 Minuspunkte

Ich mache gerade ein c# programm mit 2d figuren mit windows.drawing. Meine figuren bestehen aus punkten PointF[]. wenn ich die geometrien rotiere berechne ich direkt die punkte und setze sie neu. Jetzt will ich aber einen property für die rotation einführen um sie zurücksezuen zu können.

private double rotation = 0;
public double Rotation
{
    get
    {
        return rotation;
    }
    set
    {
        if (rotation != value)
        {

            rotation = value;
            
        }
        
    }
}

In meinem programm habe ich ein propertygrid wenn ich dort die variable Rotation ändere will ich die punkte dementsprechend rotieren.

private double rotation = 0;
public double Rotation
{
    get
    {
        return rotation;
    }
    set
    {
        if (rotation != value)
        {

            if(rotation != 0)
                Rotate(-rotation);
            rotation = value;
            
        }
    }
}

Ich bekomme aber eine StackOverflowException. Und hier ist meine rotate funktion.

public void Rotate(double degrees)
{
    Rotation = degrees;

    PointF oldOrigin = Origin;
    Origin = new PointF(0, 0);

    PointF[] rotatedPoints = RotatePoints(Points, Origin, degrees);

    Points = null;
    Points = rotatedPoints;

    Origin = oldOrigin;
}

private PointF[] RotatePoints(PointF[] points, PointF origin, double angleInDegrees)
{
    double angleInRadians = angleInDegrees * (Math.PI / 180.0);

    PointF[] rotatedPoints = new PointF[points.Length];
    for (int i = 0; i < points.Length; i++)
    {
        double x = points[i].X - origin.X;
        double y = points[i].Y - origin.Y;

        double rotatedX = x * Math.Cos(angleInRadians) - y * Math.Sin(angleInRadians);
        double rotatedY = x * Math.Sin(angleInRadians) + y * Math.Cos(angleInRadians);

        rotatedPoints[i] = new PointF((float)(rotatedX + origin.X), (float)(rotatedY + origin.Y));
    }

    return rotatedPoints;
}
von  
Kannst du deine Rotate Funktion auch noch dazu posten?

1 Antwort

0 Pluspunkte 0 Minuspunkte

Die Exception wird durch die Rekursion in der Rotate Methode verursacht.Dort schreibst du

Rotation = degrees; 

was wiederum zur Ausführung der set-Methode führt und die Rotate Methode erneut aufruft. Du kannst die rotation Eigenschaft in der Rotate Methode direkt aktualisieren, ohne die set Methode aufzurufen.

von (706 Punkte)