我有一个标题窗口.当用户从下拉列表中选择一个选项时,标题图像可以改变.问题是当图像加载时,它是模糊的,拉伸的和像素化的.这些是我正在使用的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
对于参考:
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
任何人有任何想法是什么?
我可以想到两件事:
首先,尝试加载图像:
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
嘿,这个有点丑,但它只是一行:
imgTitle.Source = new BitmapImage(new Uri(@"pack://application:,,,/YourAssembly;component/your_image.png"));