Picasso ——针对 Android的一个强大的图像下载和缓存库

来源:互联网 发布:淘宝新品上架链接在哪 编辑:程序博客网 时间:2024/05/16 15:45
简介
图片为安卓应用添加了必备内容和视觉风格。Picasso允许应用程序加载图片——往往只需一行代码!
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Picasso会自动处理安卓加载图片时出现的许多常见缺陷:
1.在适配器中处理ImageView循环和下载取消。
2.保证最小内存使用率情况下的复杂图片转换。
3.自动内存和磁盘高速缓存。

特性
适配器下载
可以自动检测适配器复用
  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. }
复制代码

把该类的实例传递给变换方法。


占位符
Picasso把下载和错误占位符作为可选功能。
  1. Picasso.with(context)
  2.     .load(url)
  3.     .placeholder(R.drawable.user_placeholder)
  4.     .error(R.drawable.user_placeholder_error)
  5.     .into(imageView);
复制代码

在显示错误占位符前请求会重试三次。

资源加载
资源,资产,文件,内容供应商均可作为图像源。
  1. Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
  2. Picasso.with(context).load(new File(...)).into(imageView2);
复制代码

DEBUG指标
开发时可以启用彩带来指示图像源。在Picasso实例中调用setIndicatorsEnabled(true)。

Download
 picasso-2.4.0.jar (112.05 KB, 下载次数: 5)

  1. MAVEN
  2. <dependency>
  3.   <groupId>com.squareup.picasso</groupId>
  4.   <artifactId>picasso</artifactId>
  5.   <version>2.4.0</version>
  6. </dependency>
复制代码

原文:http://square.github.io/picasso/
翻译作者:eoe - @wanning
转载请注明:文章转载自eoeAndroid社区( http://www.eoeandroid.com
0 0
原创粉丝点击