gpt4 book ai didi

c# - 获取 RotateTransform 的结果大小

转载 作者:行者123 更新时间:2023-11-30 22:10:08 27 4
gpt4 key购买 nike

我有以下用于在 C# 中旋转图像的代码:

private Bitmap RotateImage(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.TranslateTransform((float)returnBitmap.Width / 2, (float)returnBitmap.Height / 2);

//rotate
g.RotateTransform(angle);
//move image back
g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
//draw passed in image onto graphics object
g.DrawImage(b, new Rectangle(new Point(0, 0), new Size(b.Width, b.Height)));
return returnBitmap;
}

它工作得很好,除了它会在超出原始边界时裁剪结果。

据我了解,我必须将 returnBitmap 的大小设置为旋转后的图像大小。但是我如何知道结果有多大,从而相应地设置新位图的大小?

最佳答案

您需要旋转原始图像的四个角并计算新坐标的边界框:

    private static Bitmap RotateImage(Image b, float angle)
{
var corners = new[]
{new PointF(0, 0), new Point(b.Width, 0), new PointF(0, b.Height), new PointF(b.Width, b.Height)};

var xc = corners.Select(p => Rotate(p, angle).X);
var yc = corners.Select(p => Rotate(p, angle).Y);

//create a new empty bitmap to hold rotated image
Bitmap returnBitmap = new Bitmap((int)Math.Abs(xc.Max() - xc.Min()), (int)Math.Abs(yc.Max() - yc.Min()));
...
}

/// <summary>
/// Rotates a point around the origin (0,0)
/// </summary>
private static PointF Rotate(PointF p, float angle)
{
// convert from angle to radians
var theta = Math.PI*angle/180;
return new PointF(
(float) (Math.Cos(theta)*(p.X) - Math.Sin(theta)*(p.Y)),
(float) (Math.Sin(theta)*(p.X) + Math.Cos(theta)*(p.Y)));
}

关于c# - 获取 RotateTransform 的结果大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21066152/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com