WPF使用的BitmapImage作为源TransformedBitmap

问题描述 投票:0回答:1

在我的WPF我创建了一个名为“image_box”的imagebox

在Window_Loaded我加载我imagebox与

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

我有下一个代码上Rotate_Click(对象发件人,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 =新URI( “包://应用:,,, /图像/ pic.png”);

使用

image_box的位置一样

bmp.UriSource = image_box.Source;

我尝试

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

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

c# wpf visual-studio-2017
1个回答
0
投票

表达方式

image_box.Source.ToString()

只有当Source是BitmapImage的返回一个有效的URI字符串。然而,在你的Click处理程序的第二个电话,源是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);
}
© www.soinside.com 2019 - 2024. All rights reserved.