WPF图像在运行时动态更改图像源

时间:2008-12-29 04:12:23

标签: wpf image dynamic execution

我有一个标题窗口。当用户从下拉列表中选择一个选项时,标题图像可以改变。问题是当图像加载时,它是模糊的,拉伸的和像素化的。这些是我正在使用的PNG文件,它们在动态设置源之前看起来很好。

这是我用来更改图片来源的代码。

string strUri2 = String.Format(@"pack://application:,,,/MyAssembly;component/resources/main titles/{0}", CurrenSelection.TitleImage);
Stream iconStream2 = App.GetResourceStream(new Uri(strUri2)).Stream;
imgTitle.Source = HelperFunctions.returnImage(iconStream2);

以下是辅助函数。

    public static BitmapImage returnImage(Stream iconStream)
    {
        Bitmap brush = new Bitmap(iconStream);
        System.Drawing.Image img = brush.GetThumbnailImage(brush.Height, brush.Width, null, System.IntPtr.Zero);
        var imgbrush = new BitmapImage();
        imgbrush.BeginInit();
        imgbrush.StreamSource = ConvertImageToMemoryStream(img);
        imgbrush.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
        imgbrush.EndInit();
        var ib = new ImageBrush(imgbrush);
        return imgbrush;
    }

    public static MemoryStream ConvertImageToMemoryStream(System.Drawing.Image img)
    {
        var ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms;
    }

和XAML

            <Image x:Name="imgTitle" HorizontalAlignment="Left" VerticalAlignment="Bottom" Grid.Column="1" Grid.Row="1" Stretch="None" d:IsLocked="False"/>

对于Ref:

xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 

任何人都有任何想法是什么?

6 个答案:

答案 0 :(得分:26)

我可以想到两件事:

首先,尝试使用以下方式加载图像:

string strUri2 = String.Format(@"pack://application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
imgTitle.Source = new BitmapImage(new Uri(strUri2));

问题可能是WinForm的图像调整大小,如果图像被拉伸,请将图像控件上的Stretch设置为“Uniform”或“UnfirofmToFill”。

第二个选项是图像可能没有与像素网格对齐,您可以在http://www.nbdtech.com/blog/archive/2008/11/20/blurred-images-in-wpf.aspx

的博客上阅读它。

答案 1 :(得分:10)

嘿,这个有点丑,但只有一行:

imgTitle.Source = new BitmapImage(new Uri(@"pack://application:,,,/YourAssembly;component/your_image.png"));

答案 2 :(得分:4)

以下是它如何为我精美工作。 在窗口资源中添加图像。

   <Image x:Key="delImg" >
    <Image.Source>
     <BitmapImage UriSource="Images/delitem.gif"></BitmapImage>
    </Image.Source>
   </Image>

然后代码就是这样。

Image img = new Image()

img.Source = ((Image)this.Resources["delImg"]).Source;

“this”指的是Window对象

答案 3 :(得分:3)

喜欢我 - &gt;工作是:

string strUri2 = Directory.GetCurrentDirectory()+@"/Images/ok_progress.png"; image1.Source = new BitmapImage(new Uri(strUri2));

答案 4 :(得分:2)

在图像上尝试Stretch =“UniformToFill”

答案 5 :(得分:2)

Me.imgAddNew.Source = New System.Windows.Media.Imaging.BitmapImage(New Uri("/SPMS;component/Images/Cancel__Red-64.png", UriKind.Relative))
相关问题