Picasso官方网址:http://square.github.io/picasso/
介绍
在Android应用程序中使用Picasso添加图片必须要有上下文(context)和图片来源。仅仅只需要一行代码就能完全实现图片的异步加载!
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Picasso能帮你处理许多在Android图片加载中遇到的常见问题:
- 在adapter中需要取消已经不在视野范围的ImageView图片资源的加载(避免导致图片错位)。
- 使用复杂的图片压缩转换来尽可能的减少内存消耗。
- 自带内存和硬盘二级缓存功能。
特性
Adapter中的下载
Adapter的重用会被自动检测到,Picasso会取消上次的加载。
@Override public void getView(int position, View convertView, ViewGroup parent) {
SquaredImageView view = (SquaredImageView) convertView;
if (view == null) {
view = new SquaredImageView(context);
}
String url = getItem(position);
Picasso.with(context).load(url).into(view);
}
图像转换
转换图像更好地适应布局和减少内存开销。
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
您还可以通过自定义转换实现更多不同的效果。
public class CropSquareTransformation implements Transformation {
@Override public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
if (result != source) {
source.recycle();
}
return result;
}
@Override public String key() { return "square()"; }
}
将CropSquareTransformation 的对象传递给transform
方法即可。
Place holders(占位图)
Picasso提供了两种占位图片,加载未完成或者加载发生错误的占位图,这两个为可选属性。
Picasso.with(context)
.load(url)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);
如果加载发生错误会重复三次请求,三次都失败才会显示erro Place holder。
加载资源
资源(Resources)、资产文件(assets),文件(files),内容提供者(content providers)都能作为图片来源。
Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
Picasso.with(context).load(new File(...)).into(imageView3);
调试标志
在开发过程中您可以使用彩色丝带(左上角)来标志图片的来源。调用Picasso中的 setIndicatorsEnabled(true)
来实现。
MAVEN
<dependency>
<groupId>com.squareup.picasso</groupId>
<artifactId>picasso</artifactId>
<version>(insert latest version)</version>
</dependency>
GRADLE
compile 'com.squareup.picasso:picasso:(insert latest version)'