2008-12-29 121 views
24

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

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

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"/> 

而对于参考:

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

任何人有任何想法是怎么回事?

回答

26

我能想到的两件事情:

首先,尝试加载图像:

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

也许问题是WinForm中的形象调整大小,如果图像拉伸设置在图像控件上拉伸为“Uniform”或“UnfirofmToFill”。

第二种选择是,也许图像没有对齐像素网格,你可以在http://www.nbdtech.com/blog/archive/2008/11/20/blurred-images-in-wpf.aspx

+0

感谢您的链接,非常好的博客文章。 – frameworkninja 2010-08-11 06:31:22

2

尽量拉伸= “UniformToFill” 的形象

+0

都能跟得上没有奏效。 – 2008-12-29 06:54:14

10

嘿我的博客上读到它,这个人是一种丑陋,但它只有一行:

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

如果你有你的图像在一个子文件夹把ico.Source =新的BitmapImage(新的Uri(@“pack:// application:,,, YourAssembly; component/YourFolder/your_image.png”)); – 2009-09-28 22:43:55

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; 

“这” 指的是Window对象

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

像我 - >工作是:

string strUri2 = Directory.GetCurrentDirectory()[email protected]"/Images/ok_progress.png"; image1.Source = new BitmapImage(new Uri(strUri2));

+0

在以下代码中BlackPlayerPic是Image类型。 BitmapImage activeBlackPlayer = new BitmapImage(new Uri(“C:\\ png \\ turn_black.png”)); BlackPlayerPic.Source = activeBlackPlayer; – 2015-04-30 08:00:09