Picasso的使用

Picasso的基本使用

picasso僅需一行代碼就能實(shí)現(xiàn)圖片的異步加載

Picasso.with(context).load("網(wǎng)址url").into(imageView);

Picasso不僅實(shí)現(xiàn)了圖片異步加載的功能,還解決了android中加載圖片時(shí)需要解決的一些常見問題:

  1. 在adapter中需要取消已經(jīng)不在視野范圍的ImageView圖片資源的加載,否則會(huì)導(dǎo)致圖片錯(cuò)位,Picasso已經(jīng)解決了這個(gè)問題。
  2. 使用復(fù)雜的圖片壓縮轉(zhuǎn)換來盡可能的減少內(nèi)存消耗
  3. 自帶內(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);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容