Rotate image around center itself

I am developing an application in C # and would like to know how to freely rotate a bitmap that is drawn on a pictureBox without rotating the entire _pictureBox_e so that the bitmap rotate around your own Center . Follow 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 did not get the expected result, as the image "orbits" around the specified point, however I would like the image to rotate around your own center. Can anyone help with this problem?

Author: Felipe Mateus, 2019-01-21

1 answers

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 only need to provide the Bitmap and the angle you want to rotate the image, then picking up the result.


More details in the question Rotating image around center C# available in SOen.

 1
Author: João Martins, 2019-01-21 12:44:13