Picasso的基本使用
picasso僅需一行代碼就能實現圖片的異步加載
Picasso.with(context).load("網址url").into(imageView);
Picasso不僅實現了圖片異步加載的功能,還解決了android中加載圖片時需要解決的一些常見問題:
- 在adapter中需要取消已經不在視野範圍的ImageView圖片資源的加載,否則會導致圖片錯位,Picasso已經解決了這個問題。
- 使用複雜的圖片壓縮轉換來儘可能的減少內存消耗
- 自帶內存和硬盤二級緩存功能
Picasso特性
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)
也可以自定義轉換(需要繼承Transformation):
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。
資源文件的加載
除了加載網絡圖片以外,picasso還支持加載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);