简体   繁体   中英

Draw a rotated image directly to Graphics object, without creating a new Bitmap

I was able to make an image to rotate by drawing on a separate graphics object, which draws on a separate Bitmap, and then draw the bitmap with the graphics object, which draws on the final image. This is drawing two basically same images. And I don't want that. The project is a simple graphics engine, so drawing time must be as fast as possible. On top of that, System.Graphics has not proven to be too good at drawing images.

Here is the code I am using. It needs an improvement or two, but the basic method should be visible.

    public static System.Drawing.Bitmap rotatedImage(System.Drawing.Bitmap img, double deg, bool hq)
    {
        int diag = (int)Math.Round(Math.Sqrt(img.Width * img.Width + img.Height * img.Height));
        System.Drawing.Bitmap res = new System.Drawing.Bitmap(diag, diag);
        System.Drawing.Graphics gfx = System.Drawing.Graphics.FromImage(res);
        if (hq) gfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        DoublePair rotCent = new DoublePair(diag / 2, diag / 2);
        gfx.TranslateTransform((float)rotCent.a, (float)rotCent.b);
        gfx.RotateTransform((float)deg);
        gfx.TranslateTransform((-1) * (float)rotCent.a, (-1) * (float)rotCent.b);
        gfx.DrawImage(img, (diag - img.Width) / 2, (diag - img.Height) / 2, img.Width, img.Height);
        return res;
    }

Drawing a rotated image on a new Bitmap requires to rotate the graphics object, which is used for drawing. What I can do is pass the main graphics object to the method, rotate it to draw the image and then rotate the object back. But I don't know if rotating a graphics for a large image is faster or slower than rotating a graphics for a small image.

So, which is going to be faster - to rotate the whole graphics object twice (rotate to draw the image and then rotate back), or to draw the rotated image with a separate graphics and then draw it with the main graphics object? Is there an option to rotate an image without having to use a separate graphics object and without having to rotate a graphics object?

What I did in the last project was this one, this is inside Paint event, you dont need to create new bitmap, just reset transform and draw the image again:

e.Graphics.ResetTransform();
e.Graphics.TranslateTransform(Width/2, Height/2);
e.Graphics.RotateTransform(45f);  //45 degree
e.Graphics.DrawImage(.... //original image

e.Graphics.ResetTransform();
e.Graphics.TranslateTransform(Width/2, Height/2);
e.Graphics.RotateTransform(60f);  //60degree
e.Graphics.DrawImage(.... //original image
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM