picasso-强大的Android图片下载缓存库

 picassoSquare公司开源的一个Android图形缓存库,地址http://square.github.io/picasso/,可以实现图片下载和缓存功能。仅仅只需要一行代码就能完全实现图片的异步加载:

 
 
  1. Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

  Api看起来非常独特,是吧。

Sample application screenshot.

    Picasso不仅实现了图片异步加载的功能,还解决了android中加载图片时需要解决的一些常见问题:

   1.adapter中需要取消已经不在视野范围的ImageView图片资源的加载,否则会导致图片错位,Picasso已经解决了这个问题

   2.使用复杂的图片压缩转换来尽可能的减少内存消耗

   3.自带内存和硬盘二级缓存功能

 特性以及示例代码:

        ADAPTER 中的下载Adapter的重用会被自动检测到,Picasso会取消上次的加载

 
 
  1. @Override public void getView(int position, View convertView, ViewGroup parent) {
  2. SquaredImageView view = (SquaredImageView) convertView;
  3. if (view == null) {
  4. view = new SquaredImageView(context);
  5. }
  6. String url = getItem(position);
  7. Picasso.with(context).load(url).into(view);
  8. }

   图片转换:转换图片以适应布局大小并减少内存占用

 
 
  1. Picasso.with(context)
  2. .load(url)
  3. .resize(50, 50)
  4. .centerCrop()
  5. .into(imageView);

   你还可以自定义转换:

 
 
  1. public class CropSquareTransformation implements Transformation {
  2. @Override public Bitmap transform(Bitmap source) {
  3. int size = Math.min(source.getWidth(), source.getHeight());
  4. int x = (source.getWidth() - size) / 2;
  5. int y = (source.getHeight() - size) / 2;
  6. Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
  7. if (result != source) {
  8. source.recycle();
  9. }
  10. return result;
  11. }
  12. @Override public String key() { return "square()"; }
  13. }

   将CropSquareTransformation 的对象传递给transform 方法即可。


   Place holders-空白或者错误占位图片:picasso提供了两种占位图片,未加载完成或者加载发生错误的时需要一张图片作为提示。

 
 
  1. Picasso.with(context)
  2. .load(url)
  3. .placeholder(R.drawable.user_placeholder)
  4. .error(R.drawable.user_placeholder_error)
  5. .into(imageView);

   如果加载发生错误会重复三次请求,三次都失败才会显示erro Place holder

   资源文件的加载:除了加载网络图片picasso还支持加载Resources, assets, files, content providers中的资源文件。

 
 
  1. Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
  2. Picasso.with(context).load(new File(...)).into(imageView2);


下面是picasso源码的解析(不看不影响使用)

Cache,缓存类



Lrucacha,主要是get和set方法,存储的结构采用了LinkedHashMap,这种map内部实现了lru算法(Least Recently Used 近期最少使用算法)。
 
 
  1. this.map = new LinkedHashMap<String, Bitmap>(0, 0.75f, true);
最后一个参数的解释:
true if the ordering should be done based on the last access (from least-recently accessed to most-recently accessed), and false if the ordering should be the order in which the entries were inserted.
因为可能会涉及多线程,所以在存取的时候都会加锁。而且每次set操作后都会判断当前缓存区是否已满,如果满了就清掉最少使用的图形。代码如下
 
 
  1. private void trimToSize(int maxSize) {
  2. while (true) {
  3. String key;
  4. Bitmap value;
  5. synchronized (this) {
  6. if (size < 0 || (map.isEmpty() && size != 0)) {
  7. throw new IllegalStateException(getClass().getName()
  8. + ".sizeOf() is reporting inconsistent results!");
  9. }
  10. if (size <= maxSize || map.isEmpty()) {
  11. break;
  12. }
  13. Map.Entry<String, Bitmap> toEvict = map.entrySet().iterator()
  14. .next();
  15. key = toEvict.getKey();
  16. value = toEvict.getValue();
  17. map.remove(key);
  18. size -= Utils.getBitmapBytes(value);
  19. evictionCount++;
  20. }
  21. }
  22. }

Request,操作封装类



所有对图形的操作都会记录在这里,供之后图形的创建使用,如重新计算大小,旋转角度,也可以自定义变换,只需要实现Transformation,一个bitmap转换的接口。
 
 
  1. public interface Transformation {
  2. /**
  3. * Transform the source bitmap into a new bitmap. If you create a new bitmap instance, you must
  4. * call {@link android.graphics.Bitmap#recycle()} on {@code source}. You may return the original
  5. * if no transformation is required.
  6. */
  7. Bitmap transform(Bitmap source);
  8. /**
  9. * Returns a unique key for the transformation, used for caching purposes. If the transformation
  10. * has parameters (e.g. size, scale factor, etc) then these should be part of the key.
  11. */
  12. String key();
  13. }

当操作封装好以后,会将Request传到另一个结构中Action。

Action


Action代表了一个具体的加载任务,主要用于图片加载后的结果回调,有两个抽象方法,complete和error,也就是当图片解析为bitmap后用户希望做什么。最简单的就是将bitmap设置给imageview,失败了就将错误通过回调通知到上层。


ImageViewAction实现了Action,在complete中将bitmap和imageview组成了一个PicassoDrawable,里面会实现淡出的动画效果。


 
 
  1. @Override
  2. public void complete(Bitmap result, Picasso.LoadedFrom from) {
  3. if (result == null) {
  4. throw new AssertionError(String.format(
  5. "Attempted to complete action with no result!\n%s", this));
  6. }
  7. ImageView target = this.target.get();
  8. if (target == null) {
  9. return;
  10. }
  11. Context context = picasso.context;
  12. boolean debugging = picasso.debugging;
  13. PicassoDrawable.setBitmap(target, context, result, from, noFade,
  14. debugging);
  15. if (callback != null) {
  16. callback.onSuccess();
  17. }
  18. }

有了加载任务,具体的图片下载与解析是在哪里呢?这些都是耗时的操作,应该放在异步线程中进行,就是下面的BitmapHunter。

BitmapHunter



BitmapHunter是一个Runnable,其中有一个decode的抽象方法,用于子类实现不同类型资源的解析。


 
 
  1. @Override
  2. public void run() {
  3. try {
  4. Thread.currentThread()
  5. .setName(Utils.THREAD_PREFIX + data.getName());
  6. result = hunt();
  7. if (result == null) {
  8. dispatcher.dispatchFailed(this);
  9. } else {
  10. dispatcher.dispatchComplete(this);
  11. }
  12. } catch (IOException e) {
  13. exception = e;
  14. dispatcher.dispatchRetry(this);
  15. } catch (Exception e) {
  16. exception = e;
  17. dispatcher.dispatchFailed(this);
  18. } finally {
  19. Thread.currentThread().setName(Utils.THREAD_IDLE_NAME);
  20. }
  21. }
  22. abstract Bitmap decode(Request data) throws IOException;
  23. Bitmap hunt() throws IOException {
  24. Bitmap bitmap;
  25. if (!skipMemoryCache) {
  26. bitmap = cache.get(key);
  27. if (bitmap != null) {
  28. stats.dispatchCacheHit();
  29. loadedFrom = MEMORY;
  30. return bitmap;
  31. }
  32. }
  33. bitmap = decode(data);
  34. if (bitmap != null) {
  35. stats.dispatchBitmapDecoded(bitmap);
  36. if (data.needsTransformation() || exifRotation != 0) {
  37. synchronized (DECODE_LOCK) {
  38. if (data.needsMatrixTransform() || exifRotation != 0) {
  39. bitmap = transformResult(data, bitmap, exifRotation);
  40. }
  41. if (data.hasCustomTransformations()) {
  42. bitmap = applyCustomTransformations(
  43. data.transformations, bitmap);
  44. }
  45. }
  46. stats.dispatchBitmapTransformed(bitmap);
  47. }
  48. }
  49. return bitmap;
  50. }
可以看到,在decode生成原始bitmap,之后会做需要的转换transformResult和applyCustomTransformations。最后在将最终的结果传递到上层dispatcher.dispatchComplete(this)。
基本的组成元素有了,那这一切是怎么连接起来运行呢,答案是Dispatcher。

Dispatcher任务调度器

在bitmaphunter成功得到bitmap后,就是通过dispatcher将结果传递出去的,当然让bitmaphunter执行也要通过Dispatcher。


Dispatcher内有一个HandlerThread,所有的请求都会通过这个thread转换,也就是请求也是异步的,这样应该是为了Ui线程更加流畅,同时保证请求的顺序,因为handler的消息队列。
外部调用的是dispatchXXX方法,然后通过handler将请求转换到对应的performXXX方法。
例如生成Action以后就会调用dispather的dispatchSubmit()来请求执行,
 
 
  1. void dispatchSubmit(Action action) {
  2. handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
  3. }

handler接到消息后转换到performSubmit方法

 
 
  1. void performSubmit(Action action) {
  2. BitmapHunter hunter = hunterMap.get(action.getKey());
  3. if (hunter != null) {
  4. hunter.attach(action);
  5. return;
  6. }
  7. if (service.isShutdown()) {
  8. return;
  9. }
  10. hunter = forRequest(context, action.getPicasso(), this, cache, stats,
  11. action, downloader);
  12. hunter.future = service.submit(hunter);
  13. hunterMap.put(action.getKey(), hunter);
  14. }
这里将通过action得到具体的BitmapHunder,然后交给ExecutorService执行。
下面是Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView)的过程,
 
 
  1. public static Picasso with(Context context) {
  2. if (singleton == null) {
  3. singleton = new Builder(context).build();
  4. }
  5. return singleton;
  6. }
  7. public Picasso build() {
  8. Context context = this.context;
  9. if (downloader == null) {
  10. downloader = Utils.createDefaultDownloader(context);
  11. }
  12. if (cache == null) {
  13. cache = new LruCache(context);
  14. }
  15. if (service == null) {
  16. service = new PicassoExecutorService();
  17. }
  18. if (transformer == null) {
  19. transformer = RequestTransformer.IDENTITY;
  20. }
  21. Stats stats = new Stats(cache);
  22. Dispatcher dispatcher = new Dispatcher(context, service, HANDLER,
  23. downloader, cache, stats);
  24. return new Picasso(context, dispatcher, cache, listener,
  25. transformer, stats, debugging);
  26. }

在Picasso.with()的时候会将执行所需的所有必备元素创建出来,如缓存cache、执行executorService、调度dispatch等,在load()时创建Request,在into()中创建action、bitmapHunter,并最终交给dispatcher执行。

参考:http://blog.csdn.net/xu_fu/article/details/17043231

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值