Picasso框架的使用

這裏寫圖片描述

什麼是Picasso:

強大的圖片下載和緩存的第三方庫;我覺得這就是對它最準確的描述了,至於其他特性,可以參見官網

Picasso-根據名字就知道它是跟什麼相關了(Picasso:畢加索)

Picasso:A Powerful Image Downloading and Caching Library for Android


Picasso的基本用法:

將Picasso添加進項目後,要使用它非常簡單,只需要一行代碼就能搞定:

Picasso.with(context).load(imageUrl).into(imageView);

短短的一行代碼爲我們解決了很多問題:

  • 自動將圖像緩存在本地
  • 通過圖片壓縮轉換以減少內存消耗
  • 自動處理了ImageView的回收,即自動取消不在視野範圍內的ImageView視圖資源的加載;

適配器(複用)

適配器自動發現和重用以前取消的下載:

    @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(imageUrl).resize(50,50).centerCrop().into(imageView);

自定義格式轉換:
爲了實現更多你想要圖片轉換的效果,你可以自己實現一個實現了Transformation接口的類,然後將其對象傳遞給transform()方法

 public calss myTransformation implements Transformation{
        @Overrride
        public Bitmap transform(Bitmap source){
            //對source實現自定義裁剪
        }
        @Override
        public String key(){
            return "square()";
        }

    }

圖片佔位符

所謂的佔位符圖像即當圖片未正常顯示時默認的圖片,通過placeholder()設置,Picasso也支持設置圖片顯示錯誤時顯示的默認圖片,通過error()設置

    Picasso.wint(context).load(imageUrl).placeholder(R.drawable.image_placeholder).error(R.drawable.image_error_placeholder).into(imageView);

載入本地資源

除了通過網絡下載圖片,Picasso也可以載入本地圖片資源

Picasso.with(context).load(R.drawable.icon).into(imageView);
    Picasso.with(context).load("file:///android_asset/Adnroid.png").into(imageView);

Picasso.wiht(context).load(new File(...)).into(imageView);

資源加載

資源,資產,文件,內容供應商均可作爲圖像源。

Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);

Picasso.with(context).load(new File(...)).into(imageView2);

調試(DEBUG指標)

爲了方便調試,你可以通過調用Picasso的setIndicatiorEnabled(true);可以讓不同來源的圖片顯示一個不同的色彩標記
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章