Question:
I'm developing a C# application and would like to know how to freely rotate a bitmap that is drawn in a pictureBox without rotating the entire _pictureBox_e so that the bitmap rotates around its own center . Here's my last attempt:
Bitmap irisref1;
private void pcbREFOLHOS_Paint(object sender, PaintEventArgs e)
{
e.Graphics.TranslateTransform(pcbREFOLHOS.Width / 2, pcbREFOLHOS.Height / 2);
e.Graphics.RotateTransform(contador);
e.Graphics.DrawImage(irisref1, new PointF((5 - atualdata1 - 2.5f) * 10, 0));
contador++;
//e.Graphics.DrawEllipse(new Pen(Color.White, 3), 0, 0, 150, 60);
}
This way I don't get the expected result, as the image "orbits" around the specified point, but I would like the image to rotate around its own center. Can anyone help with this problem?
Answer:
Try implementing the following method:
public static Bitmap RotateImageN(Bitmap b, float angle)
{
//Create a new empty bitmap to hold rotated image.
Bitmap returnBitmap = new Bitmap(b.Width, b.Height);
//Make a graphics object from the empty bitmap.
Graphics g = Graphics.FromImage(returnBitmap);
//move rotation point to center of image.
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
//Rotate.
g.RotateTransform(angle);
//Move image back.
g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
g.DrawImage(b, 0,0,b.Width, b.Height);
return returnBitmap;
}
Then you just need to provide the Bitmap
and the angle you want to rotate the image, then getting the result.
More details in the Rotating image around center C# issue available on SOen .