Tôi có một cửa sổ có tiêu đề trên đó. Khi người dùng chọn một lựa chọn từ danh sách thả xuống, hình ảnh tiêu đề có thể thay đổi. Vấn đề là khi tải hình ảnh, đó là một mờ, kéo dài, và pixelated. Đây là những tập tin PNG tôi đang làm việc với và họ nhìn tốt trước khi thiết lập nguồn động.Hình ảnh WPF Tự động thay đổi nguồn hình ảnh trong thời gian chạy
Đây là mã tôi đang sử dụng để thay đổi nguồn của hình ảnh.
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);
Dưới đây là các chức năng trợ giúp.
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;
}
Và XAML
<Image x:Name="imgTitle" HorizontalAlignment="Left" VerticalAlignment="Bottom" Grid.Column="1" Grid.Row="1" Stretch="None" d:IsLocked="False"/>
Và đối với Ref:
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Bất cứ ai có bất cứ ý tưởng có chuyện gì thế?
cảm ơn vì liên kết, bài đăng blog rất hay. – frameworkninja