c#图像旋转
本文关键字:旋转 图像 | 更新日期: 2023-09-27 17:59:03
我需要一些帮助来解决一个真正让我头疼的问题。它是一个允许用户加载图像文件,然后将图像顺时针或逆时针旋转90度的应用程序。代码运行良好,但如果用户顺时针旋转图像,然后决定通过逆时针将其旋转回初始位置,则图像不在应有的位置。我不确定我缺少了什么,因为我对c#非常陌生。以下是我用于顺时针旋转的代码。
private int cW = 0;
private void button6_Click(object sender, RoutedEventArgs e)
{
RotateTransform rotateTransform = new RotateTransform();
rotateTransform.CenterX = image1.ActualWidth / 2.0;
rotateTransform.CenterY = image1.ActualHeight / 2.0;
cW += 90;
rotateTransform.Angle = cW;
TransformGroup transformGroup = new TransformGroup();
transformGroup.Children.Add(rotateTransform);
image1.RenderTransform = transformGroup;
}
我已经使用if/else语句完全更改了代码。下面是我想要的结果。
RotateTransform cwRotateTransform;
private void button6_Click(object sender, RoutedEventArgs e)
{
if (cwRotateTransform == null)
{
cwRotateTransform = new RotateTransform();
}
image1.LayoutTransform = cwRotateTransform;
if (cwRotateTransform.Angle == 360)
cwRotateTransform.Angle = 0;
else cwRotateTransform.Angle += 90;
}
对于逆时针方向,只需将"90"更改为"-90"即可,否则为cwRotateTransform.Angle
。
使用图片框和使用rotateflip:的位图对我来说效果很好
Bitmap bitmapPicturebox1;
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.ImageLocation = @"C:'Wallpaper.jpg";
}
private void btnLeft_Click(object sender, EventArgs e)
{
bitmapPicturebox1 = new Bitmap(pictureBox1.Image);
bitmapPicturebox1.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox1.Image = bitmapPicturebox1;
}
private void btnRight_Click(object sender, EventArgs e)
{
bitmapPicturebox1 = new Bitmap(pictureBox1.Image);
bitmapPicturebox1.RotateFlip(RotateFlipType.Rotate270FlipNone);
pictureBox1.Image = bitmapPicturebox1;
}