Picasso的基本使用
picasso僅需一行代碼就能實(shí)現(xiàn)圖片的異步加載
Picasso.with(context).load("網(wǎng)址url").into(imageView);
Picasso不僅實(shí)現(xiàn)了圖片異步加載的功能,還解決了android中加載圖片時(shí)需要解決的一些常見問題:
- 在adapter中需要取消已經(jīng)不在視野范圍的ImageView圖片資源的加載,否則會(huì)導(dǎo)致圖片錯(cuò)位,Picasso已經(jīng)解決了這個(gè)問題。
- 使用復(fù)雜的圖片壓縮轉(zhuǎn)換來盡可能的減少內(nèi)存消耗
- 自帶內(nèi)存和硬盤二級(jí)緩存功能
Picasso特性
ADAPTER 中的下載:Adapter的重用會(huì)被自動(dòng)檢測(cè)到,Picasso會(huì)取消上次的加載
@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);
}
圖片轉(zhuǎn)換:轉(zhuǎn)換圖片以適應(yīng)布局大小并減少內(nèi)存占用
Picasso.with(context).load(url).resize(50, 50).centerCrop().into(imageView)
也可以自定義轉(zhuǎn)換(需要繼承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 的對(duì)象傳遞給transform 方法即可。
Place holders-空白或者錯(cuò)誤占位圖片
picasso提供了兩種占位圖片,未加載完成或者加載發(fā)生錯(cuò)誤的時(shí)需要一張圖片作為提示。
Picasso.with(context).load(url)
.placeholder(R.drawable.user_placeholder)//沒有加載圖片時(shí)顯示的默認(rèn)圖像
.error(R.drawable.user_placeholder_error)// 圖像加載錯(cuò)誤時(shí)顯示的圖像
.into(imageView);// 被加載的控件
注:如果加載發(fā)生錯(cuò)誤會(huì)重復(fù)三次請(qǐng)求,三次都失敗才會(huì)顯示erro Place holder。
資源文件的加載
除了加載網(wǎng)絡(luò)圖片以外,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);