문제

I guess this one is rather simple for those who use GDI more frequently. I have an image that I want to rotate.

Sample image:

before rotation

After I apply my rotation, it looks like the following:

enter image description here

Here's the code used:

public Bitmap RotateBitmap(Bitmap bitmap, float angle)
{
    using (Graphics graphics = Graphics.FromImage(bitmap))
    {
        graphics.TranslateTransform((float)bitmap.Width / 2, (float)bitmap.Height / 2);
        graphics.RotateTransform(angle);
        graphics.TranslateTransform(-(float)bitmap.Width / 2, -(float)bitmap.Height / 2);
        graphics.DrawImage(bitmap, new Point(0, 0));
    }
    return bitmap;
}

What I want to get rid of is the part of the image that remains there from before the rotation. Any attempts to use DrawRectangle and Clear before calling DrawImage gave me white images, which makes some kind of sense.

도움이 되었습니까?

해결책

Try the following:

public Bitmap RotateBitmap(Image bitmap, float angle) {
    Bitmap result = new Bitmap(bitmap.Width, bitmap.Height, bitmap.PixelFormat);
    using(Graphics graphics = Graphics.FromImage(result)) {
        graphics.TranslateTransform((float)bitmap.Width / 2f, (float)bitmap.Height / 2f);
        graphics.RotateTransform(angle);
        graphics.TranslateTransform(-(float)bitmap.Width / 2f, -(float)bitmap.Height / 2f);
        graphics.DrawImage(bitmap, Point.Empty);
    }
    return result;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top