• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
锦燕云
博客园    首页    新随笔    联系   管理    订阅  订阅

Windows Phone 7(WP7)开发 图片缓存

最近在做一个WP7的客户端,中间涉及到了从互联网上获取图片,而手机的无线网络其实很慢的(哪怕是联通的3G我也没感觉有多么快),所以缓存我想还是必不可少的吧。

其实做在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地址")); 

就可以啦。 

 

posted @ 2011-12-01 12:40  锦燕云  阅读(3543)  评论(16)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3