在Windows RT应用程序中预加载图像
本文关键字:加载 图像 应用程序 Windows RT | 更新日期: 2023-09-27 17:49:16
我有一个运行在Windows RT上的Windows Store应用程序,其中包括一个图像列表框。有相当多的他们,所以当加载他们的第一次绘画过程是相当明显的。我知道有一个缓存机制在后台运行,我想用它来预加载列表顶部的前几个图像,以便列表立即出现。
有办法吗?
我找到解决办法了。
IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);
BitmapImage bitmapImage = new BitmapImage();
if (await bitmapImage.SetSourceAsync(stream))
{
image1.source = bitmapImage;
}
让它工作,下面是我如何做到的。我创建了一个Dictionary<string, BitmapImage>
来存储预加载的图像,并在应用程序启动时加载它。还创建了一个函数,该函数接受一个路径,如果存在则从字典中返回预加载的图像,如果不存在则正常加载。
private Dictionary<string, BitmapImage> preload;
.
.
.
public void PreloadImages(BaseUri, path)
{
if (!preload.ContainsKey(path))
{
var uri = new Uri(BaseUri, path);
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
BitmapImage bmp = new BitmapImage();
if (!preload.ContainsKey(path))
preload.Add(path, bmp);
}
}
public BitmapImage ImageFromRelativePath(Uri BaseUri, string path)
{
if (preload.ContainsKey(path))
{
return preload[path];
}
else
{
var uri = new Uri(BaseUri, path);
BitmapImage bmp = new BitmapImage();
bmp.UriSource = uri;
return bmp;
}
}
然后我在Xaml绑定中使用了一个Converter
public sealed class CachedImageConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var path = value as string;
if (path == null)
return null;
var app = App.Current as App;
return app.ImageHelper.ImageFromRelativePath(new Uri("ms-appx:/"), path);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
和正在运行的转换器:
<Image Source="{Binding Path=ImagePath, Mode=OneWay, Converter={StaticResource CachedImageConverter}}"></Image>