Windows Phone 7 开发之图片缓存
国内的无线网络很悲催,所以手机在上网的时候加载图片超级慢,所以通常在开发手机客户端的时候需要做一个缓存机制,这个是如何实现的呢,今天Xushine研究院来揭开这个谜底
在WP7上面做缓存很容易,直接看代码:
<Image Height="150" Canvas.Left="8" Canvas.Top="8" Width="150" Source="{Binding PicID, Converter={StaticResource ImageConverter}, Mode=OneWay}"/>
需要注意的事:图片Image控件主要就是Source属性的设置,绑定图片的ID,并且设置好Converter。
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
ImageSource source = ImageCache.GetImage(value.ToString());
return source;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return "";
}
}
Converter中其实没什么太多内容,主要是把PICID传递给缓存类,下面是缓存代码:
public class ImageCache
{
public static Dictionary<string, ImageSource> ImageSources = new Dictionary<string, ImageSource>();
static ImageCache()
{
ImageSources.Add("", new BitmapImage(new Uri(StaticResource.PathNoImage, UriKind.Relative)));
}
public static ImageSource GetImage(string imageId)
{
if (!ImageSources.ContainsKey(imageId))
{
ImageSource source = new BitmapImage(new Uri(StaticResource.UrlPicture + imageId));
ImageSources.Add(imageId, source);
}
return ImageSources[imageId];
}
}
在这一段程序中,只是在内存中开了一个Dictionary<string, ImageSource>来进行缓存的,顺带一提:在mango里(之前版本没试过呢),从网络上获取图片不用很费劲的去写Http请求了,直接
ImageSource source = new BitmapImage(new Uri("图片的http地址"));
就可以啦。
评论被关闭。