cravie
cravie

Reputation: 35

Rotate elements towards a point

I'm having trouble figuring out the math to rotate elements I load in programatically into WPF. The problem I'm encountering is that when you load in an image, it always loads in a certain way(see image). And when I try to face the elements towards the point, their angles are always wrong because of the way they initially load in(for example, the arrow on the left will always be pointing in the wrong direction). enter image description here

I can easily solve the problem via hardcoding, but due to my requirements this can't be done as the arrows will not always be N,E,S,W. Any help would be appreciated.

Upvotes: 0

Views: 74

Answers (1)

Vordex
Vordex

Reputation: 52

You can you Math.Atan2 (https://msdn.microsoft.com/en-us/library/system.math.atan2(v=vs.110).aspx) to get an angle, and then a function to rotate image around it (there is many floating around) such as this one https://stackoverflow.com/a/12025915/767333

Edit:

this SHOULD work just fine

private Bitmap RotateImage( Bitmap bmp, float angle ) {
     Bitmap rotatedImage = new Bitmap( bmp.Width, bmp.Height );
     using ( Graphics g = Graphics.FromImage( rotatedImage ) ) {
        g.TranslateTransform( bmp.Width / 2, bmp.Height / 2 ); //set the rotation point as the center into the matrix
        g.RotateTransform( angle ); //rotate
        g.TranslateTransform( -bmp.Width / 2, -bmp.Height / 2 ); //restore rotation point into the matrix
        g.DrawImage( bmp, new Point( 0, 0 ) ); //draw the image on the new bitmap
     }

     return rotatedImage;
}

myBmp = RotateImage(myBmp, Math.Atan2(bmpY + myBmp.Height / 2 - middlePointY, bmpX + myBmp.Width / 2 - middlePointX));

Upvotes: 2

Related Questions