Search code examples
c#mathrotationtrigonometrysystem.drawing

Lines rotation problem


I have 2 lines that i draw like this:

float Alpha = RotDegrees;
PointF PitCenter = new Point(picBoxZoomMap.Width / 2, picBoxZoomMap.Height / 2);
PointF p = new PointF(PitCenter.X - 20, PitCenter.Y - 250);
PointF p2 = new PointF(PitCenter.X + 20, PitCenter.Y - 250);

zoomgfx.DrawLine(Pens.Red, PitCenter, new PointF(
    (float)((p.Y - PitCenter.Y) * Math.Sin(Alpha * Math.PI / 180) + p.X),
    (float)(PitCenter.Y + (p.Y - PitCenter.Y) * Math.Cos(Alpha * Math.PI / 180))));

zoomgfx.DrawLine(Pens.Red, PitCenter, new PointF(
    (float)((p2.Y - PitCenter.Y) * Math.Sin(Alpha * Math.PI / 180) + p2.X),
    (float)(PitCenter.Y + (p2.Y - PitCenter.Y) * Math.Cos(Alpha * Math.PI / 180))));

Here are the lines when Alpha = 0;

enter image description here

And here are the lines after 90 degrees rotation..

enter image description here

As you see the lines somehow meets.. i really cant understand why.. Any ideas?


Solution

  • Your formula for the rotation is incorrect, have a look here --> Rotate a point by another point in 2D

    Change your code to this, and you will get the right effect:

    PointF PitCenter = new Point(picBoxZoomMap.Width / 2, picBoxZoomMap.Height / 2);
    PointF p = new PointF(PitCenter.X - 20, PitCenter.Y - 250);
    PointF p2 = new PointF(PitCenter.X + 20, PitCenter.Y - 250);
    
    var AlphaRad = RotDegrees * Math.PI / 180;
    
    zoomgfx.DrawLine(Pens.Red, PitCenter, new PointF(
    (float)(Math.Cos(AlphaRad) * (p.X - PitCenter.X) - Math.Sin(AlphaRad) * (p.Y - PitCenter.Y) + PitCenter.X),
    (float)(Math.Sin(AlphaRad) * (p.X - PitCenter.X) + Math.Cos(AlphaRad) * (p.Y - PitCenter.Y) + PitCenter.Y)));
    
    zoomgfx.DrawLine(Pens.Red, PitCenter, new PointF(
    (float)(Math.Cos(AlphaRad) * (p2.X - PitCenter.X) - Math.Sin(AlphaRad) * (p2.Y - PitCenter.Y) + PitCenter.X),
    (float)(Math.Sin(AlphaRad) * (p2.X - PitCenter.X) + Math.Cos(AlphaRad) * (p2.Y - PitCenter.Y) + PitCenter.Y)));