天天看點

Picasso網絡圖檔加載架構的使用

官網:http://square.github.io/picasso/

  • 介紹

  • 常用用法

    在ListView 或者RecycleView的擴充卡中的使用:
@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(, )
    //剪切位置設定
    .centerCrop()
    //設定裝載圖檔的ImageView控件
    .into(imageView)
               
    自定義圖檔轉換:
    //自定義轉換類,在transform方法中實作具體轉換邏輯
    public static class CropSquareTransformation implements Transformation {
        @Override
        public Bitmap transform(Bitmap source) {
            int size = Math.min(source.getWidth(), source.getHeight());
            int x = (source.getWidth() - size) / ;
            int y = (source.getHeight() - size) / ;
            Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
            if (result!=null){
                source.recycle();
            }
            return result;
        }
    
    
        @Override
        public String key() {
            return "square()";
        }
    }
    
    ======================================================================================
    
    //使用方法
    Picasso.with(context).load(url).transform(new CropSquareTransformation()).into(imageView);
               
  • 設定加載失敗和正在加載的圖檔

    Picasso.with(context)
    .load(url)
    //設定加載過程中的圖檔顯示
    .placeholder(R.drawable.user_placeholder)
    //設定加載失敗的圖檔顯示
    .error(R.drawable.user_placeholder_error)
    .into(imageView);
               
  • 設定不同途徑的圖檔資源

//項目資源檔案夾中的圖檔
    Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
    //指定目錄下的圖檔資源
    Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
    //通過建立File對象設定圖檔
    Picasso.with(context).load(new File(...)).into(imageView3);
           
  • 設定自定義下載下傳器

源碼中自帶的下載下傳類,支援OkHttp的前提下會使用這個類,但是如果需要自定義磁盤緩存路徑,需要執行

“public OkHttpDownloader(final File cacheDir)”構造方法。

final class Utils {
    //建立預設下載下傳器
    static Downloader createDefaultDownloader(Context context) {
        try {
          //檢查是否存在OKhttp,不存在就使用 UrlConnectionDownloader
          Class.forName("com.squareup.okhttp.OkHttpClient");
          return OkHttpLoaderCreator.create(context);
        } catch (ClassNotFoundException ignored) {
        }
        return new UrlConnectionDownloader(context);
      }
        //建立預設緩存路徑
      static File createDefaultCacheDir(Context context) {
        File cache = new File(context.getApplicationContext().getCacheDir(), PICASSO_CACHE);
        if (!cache.exists()) {
          //noinspection ResultOfMethodCallIgnored
          cache.mkdirs();
        }
        return cache;
      }
}
==========================================================================
public class OkHttpDownloader implements Downloader {

     ...

  public OkHttpDownloader(final File cacheDir) {
    this(cacheDir, Utils.calculateDiskCacheSize(cacheDir));
  }


  public OkHttpDownloader(final Context context, final long maxSize) {
    this(Utils.createDefaultCacheDir(context), maxSize);
  }

  public OkHttpDownloader(final File cacheDir, final long maxSize) {
    this(defaultOkHttpClient());
    try {
      client.setCache(new com.squareup.okhttp.Cache(cacheDir, maxSize));
    } catch (IOException ignored) {
    }
  }
           

用法:

Picasso.setSingletonInstance(new Picasso
                .downloader(new OkHttpDownloader("自定義目錄,傳回File"))
                .build());
           

Picasso擷取緩存預設通過Okhttp擷取,而Okhttp使用的緩存是基于DiskLruCache,DiskLruCache的實作原理比較暈,通過讀寫journal檔案來對緩存檔案進行操作的,是以在設定了自定義目錄下,就可以通過DiskLruCache來進行擷取和清理緩存了。

Picasso網絡圖檔加載架構的使用
  • 對記憶體緩存的操作

Picasso.with(context)
    .load(url)
    //緩存方案,NO_CACHE 直接從網絡擷取,NO_STORE 不緩存在 Cache中(記憶體)
    .memoryPolicy(NO_CACHE, NO_STORE)
    .into(imageView);
           
  • 暫停、繼續加載操作

    在ListView 和 RecycleView滑動時為了避免卡頓,可以暫停請求,當控件停止滑動時繼續加載:
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState){
                    case  AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        Picasso.with(MainActivity.this).resumeTag(tag);
                        break;
                    default:
                        Picasso.with(MainActivity.this).pauseTag(tag);
                        break;
                }
            }

          ....
        });
    }
           

繼續閱讀