Rotate a Graphics bitmap at its center

To draw a rotated Bitmap you need to do a few steps to prepare the Graphics object:

  • first you move its origin onto the midpoint of the rotation
  • then you rotate by the desired angle
  • next you move it back
  • now you can draw the Bitmap
  • finally you reset the Graphics

This needs to be done for each bitmap.

Here are the steps in code to draw a Bitmap bmp at position (xPos, yPos):

float moveX = bmp.Width / 2f + xPos;   
float moveY = bmp.Height / 2f+ xPosf;   
e.Graphics.TranslateTransform(moveX , moveY );
e.Graphics.RotateTransform(angle);
e.Graphics.TranslateTransform(-moveX , -moveY );
e.Graphics.DrawImage(bmp, xPos, yPos);  
e.Graphics.ResetTransform();

There is one possible complication: If your Bitmap has different dpi resolution than the screen i.e. than the Graphics you must first adapt the Bitmap‘s dpi setting!

To adapt the Bitmapto the usual 96dpi you can simply do a

bmp.SetResolution(96,96);

To be prepared for future retina-like displays you can create a class variable you set at startup:

int ScreenDpi = 96;
private void Form1_Load(object sender, EventArgs e)
{
  using (Graphics G = this.CreateGraphics()) ScreenDpi = (int)G.DpiX;
}

and use it after loading the Bitmap:

bmp.SetResolution(ScreenDpi , ScreenDpi );

As usual the DrawImage method uses the top left corner of the Bitmap. You may need to use different Points for the rotation point and possibly also for the virtual position of your car, maybe in the middle of its front..

Leave a Comment