我有一個帶有標題的窗口。當用戶從下拉列表中選擇一個選項時,標題圖像可以改變。問題是當圖像加載時,它是模糊的,拉伸的和像素化的。這些是我正在使用的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"
任何人有任何想法是怎麼回事?
感謝您的鏈接,非常好的博客文章。 – frameworkninja 2010-08-11 06:31:22