0
点赞
收藏
分享

微信扫一扫

android:强大的图片下载和缓存库Picasso


1.Picasso简介

Picasso是Square公司出品的一个强大的图片下载和缓存图片库。官方网址是:http://square.github.io/picasso/

只需要一句代码就可以将图片下载并设置到ImageView上。


[java]  view plain copy



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




2.主要特点

2.1Adapter downloads

使用ListView,GridView的时候,自动检测Adapter的重用(re-use),取消下载,使用缓存。



[java]  view plain copy



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



2.2图像处理与变换

将图像进行变换,以更好的适应布局控件等,减小内存开销。



[java]  view plain copy



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



当然,我们也可以写自己的变换类,但是必须实现Transformation接口,如:



[java]  view plain copy



  1. /**
  2.      * 自定义接口,实现图像缩小为原来的一半
  3.      */  
  4. public class CropSquareTransformation implements Transformation {  
  5. @Override  
  6. public Bitmap transform(Bitmap source) {  
  7. int size = Math.min(source.getWidth(), source.getHeight());  
  8. int x = (source.getWidth() - size) / 2;  
  9. int y = (source.getHeight() - size) / 2;  
  10.             Bitmap result = Bitmap.createBitmap(source, x, y, size, size);  
  11. if (result != source) {  
  12.                 source.recycle();  
  13.             }  
  14. return result;  
  15.         }  
  16.   
  17. @Override  
  18. public String key() {  
  19. return "square()";  
  20.         }  
  21.     }  



然后设置transform方法就可以了:



[java]  view plain copy



  1. Picasso.with(this).load("http://i.imgur.com/DvpvklR.png")  
  2. new CropSquareTransformation()).into(iv_test2);  



效果图如下:

android:强大的图片下载和缓存库Picasso_ide


2.3。支持设置加载之前的图片,和加载失败后的图片。

如:



[java]  view plain copy



  1. Picasso.with(this)  
  2. "http://i.imgur.com/DvpvklR.png")  
  3.         .placeholder(R.drawable.abc)  
  4.         .error(R.drawable.ic_launcher)  
  5. new CropSquareTransformation())  
  6.         .into(iv_test1);  



ImageView创建时显示abc.png,如果加载成功,显示的是DvpvklR.png,如果加载失败,显示ic_launcher.png.

2.4支持加载本地图片和sdcard中的图片文件等。



[java]  view plain copy



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



Picasso下载地址:http://square.github.io/picasso/

举报

相关推荐

0 条评论