2 回答

TA貢獻1811條經驗 獲得超6個贊
首先,如果你保存圖像,直接將綁定更改為字符串/uri,沒有 BitmapImage,不需要創建它,Wpf 為你處理 public BitmapImage Image ===> public Uri Image
并刪除 FileToBitmapImage。

TA貢獻1865條經驗 獲得超7個贊
我花了幾天的時間來找到解決這個問題的簡單方法。我需要在不凍結 UI 的情況下以高質量顯示一百多張圖像。
我嘗試了對綁定等的各種修改,最后只有通過代碼和 Source 屬性集創建 Image 控件才起作用,然后 Image 出現在界面元素樹中。
在 XAML 中只有空的 ContentControl:
<ContentControl x:Name="ImageContent"/>
在代碼中:
static readonly ConcurrentExclusiveSchedulerPair _pair = new ConcurrentExclusiveSchedulerPair();
// Works for very big images
public void LoadImage(Uri imageUri)
{
var image = new System.Windows.Controls.Image(); // On UI thread
RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality);
Task.Factory.StartNew(() =>
{
var source = new BitmapImage(imageUri); // load ImageSource
Dispatcher.RunOnMainThread(() =>
{
image.Source = source; // Set source while not in UI
// Add image in UI tree
ImageContent.Content = image; // ImageContent is empty ContentControl
ImageContent.InvalidateVisual();
});
}, default, TaskCreationOptions.LongRunning, _pair.ExclusiveScheduler);
}
使用 CacheOption OnLoad 加載圖像效果更好。
public static ImageSource BitmapFromUri(Uri source)
{
if (source == null)
return new BitmapImage(source);
using (var fs = new FileStream(source.LocalPath, FileMode.Open))
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = fs;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
bitmap.Freeze();
return bitmap;
}
}
- 2 回答
- 0 關注
- 237 瀏覽
添加回答
舉報