首页 > 解决方案 > wpf 使用 bitmapimage 作为 TransformedBitmap 的源

问题描述

在我的 wpf 中,我创建了一个名为“image_box”的图像框

在 Window_Loaded 我加载我的图像框

image_box.Source = new BitmapImage(new Uri("pack://application:,,,/images/pic.png"));

我在 Rotate_Click(object sender, RoutedEventArgs e) 上有下一个代码

BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri("pack://application:,,,/images/pic.png");
bmp.EndInit();

TransformedBitmap myRotatedBitmapSource = new TransformedBitmap();
myRotatedBitmapSource.BeginInit();
myRotatedBitmapSource.Source = bmp;
myRotatedBitmapSource.Transform = new RotateTransform(90);
myRotatedBitmapSource.EndInit();
image_box.Source = myRotatedBitmapSource;

我在这段代码中想要的只是

bmp.UriSource = new Uri("pack://application:,,,/images/pic.png");

使用

image_box 的位置,例如

bmp.UriSource = image_box.Source;

我试试

Uri ur = new Uri(image_box.Source.ToString());
...
bmp.UriSource = ur;

但是在第二次点击时我得到了无效的网址

标签: c#wpfvisual-studio-2017

解决方案


表达方式

image_box.Source.ToString()

Source仅当是 BitmapImage时才返回有效的 URI 字符串。但是,在 Click 处理程序的第二次调用中,Source 是一个TransformedBitmap.

您应该简单地重复使用原始源图像并将旋转角度增加(或减少)90 的倍数。

private BitmapImage source = new BitmapImage(new Uri("pack://application:,,,/images/pic.png"));
private double rotation = 0;

private void Rotate_Click(object sender, RoutedEventArgs e)
{
    rotation += 90;
    image_box.Source = new TransformedBitmap(source, new RotateTransform(rotation));
}

或者也保留 TransformedBitmap 并仅更改其Transform属性:

private BitmapImage source = new BitmapImage(new Uri("pack://application:,,,/images/pic.png"));
private double rotation = 0;
private TransformedBitmap transformedBitmap =
    new TransformedBitmap(source, new RotateTransform(rotation));
...
image_box.Source = transformedBitmap; // call this once
...

private void Rotate_Click(object sender, RoutedEventArgs e)
{
    rotation += 90;
    transformedBitmap.Transform = new RotateTransform(rotation);
}

推荐阅读