title: c# - Rotating and centering an image
body: <p>I have an image, which I want to rotate clockwise by a specified number of degrees.  I don't want to cut anything off, so I calculate the width and height of the new image based on the specified rotation (a rotation of 45 degrees for example requires a taller and wider image.</p>
  
  <pre><code>//Calculate required size of new image
  GraphicsPath path = new GraphicsPath();
  path.AddRectangle(new RectangleF(0f, 0f, bmpSource.Width, bmpSource.Height));
  Matrix matrix = new Matrix();
  matrix.Rotate(iRotationDegrees);
  RectangleF rctNewSize = path.GetBounds(matrix);
  
  //Create new image
  Bitmap bmpRotated = new Bitmap(Convert.ToInt32(rctNewSize.Width), Convert.ToInt32(rctNewSize.Height));
  using (Graphics g = Graphics.FromImage(bmpRotated))
  {    
      //Set rotation point to center of image
      g.TranslateTransform(bmpRotated.Width / 2, 0);
      g.RotateTransform(iRotationDegrees);
  
      //Draw the rotated image on the bitmap
      g.DrawImageUnscaled(bmpSource, 0,0); 
  }
  </code></pre>
  
  <p>With an angle of 45 degrees, when I set the TranslateTransform to bmpRotated.Width / 2, 0 the rotated image is not quite centered horizontally, and the bottom left corner is cut off a bit.</p>
  
  <p>I'm missing some math here that is correctly figuring out the appropriate dx/dy values to pass to TranslateTransform.  </p>