我不确定为什么它不起作用......
Bitmap img = (Bitmap)Properties.Resources.myBitmap.Clone();
Graphics g = Graphics.FromImage(img);
g.RotateTransform(45);
pictureBox1.Image = img;
显示图像,但不旋转。
您正在旋转图形界面,但不使用它来绘制图像。图片框控件很简单,可能不是你的朋友。
尝试使用g.DrawImage(...)
see here来显示图像
一个使用Graphics
实例绘制。对Graphics
实例的更改仅在绘制到该对象时影响用于创建Graphics
实例的对象。这包括转型。简单地从位图对象创建Graphics
实例并更改其变换将不会产生任何影响(如您所见)。
以下方法将创建一个新的Bitmap
对象,传递给它的原始旋转版本:
private Image RotateImage(Bitmap bitmap)
{
PointF centerOld = new PointF((float)bitmap.Width / 2, (float)bitmap.Height / 2);
Bitmap newBitmap = new Bitmap(bitmap.Width, bitmap.Height, bitmap.PixelFormat);
// Make sure the two coordinate systems are the same
newBitmap.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution);
using (Graphics g = Graphics.FromImage(newBitmap))
{
Matrix matrix = new Matrix();
// Rotate about old image center point
matrix.RotateAt(45, centerOld);
g.Transform = matrix;
g.DrawImage(bitmap, new Point());
}
return newBitmap;
}
你可以像这样使用它:
pictureBox1.Image = RotateImage(Properties.Resources.myBitmap);
但是,您会注意到,由于新位图与旧位图具有相同的尺寸,因此在新位图内旋转图像会导致边缘裁剪。
你可以通过根据旋转计算位图的新边界来解决这个问题(如果需要......从你的问题来看,这是不是很清楚);将位图的角点传递给Matrix.TransformPoints()
方法,然后找到X和Y坐标的最小值和最大值以创建新的边界矩形,最后使用宽度和高度创建一个新的位图,您可以在其中旋转旧的位图一个没有裁剪。
最后,请注意,这一切都非常复杂,主要是因为您使用的是Winforms。 WPF对旋转视觉元素提供了更好的支持,而这一切都可以通过操作用于显示位图的WPF Image
控件来完成。