android 圖片加載和緩存開源項目 Picasso

Picasso – Android系統的圖片下載和緩存類庫

Picasso 是Square開源的一個用於Android系統下載和緩存圖片的項目。該項目和其他一些下載圖片項目的主要區別之一是:使用4.0+系統上的HTTP緩存來代替磁盤緩存。

Picasso 的使用是非常簡單的,例如:

幫助 

Picasso.with(context).load(" http://i.imgur.com/DvpvklR.png.into(imageView")); 
Picasso有如下特性:

處理Adapter中的 ImageView 回收和取消已經回收ImageView的下載進程 
使用最少的內存完成複雜的圖片轉換,比如把下載的圖片轉換爲圓角等 
自動添加磁盤和內存緩存 
具體介紹

在Adapter中下載

自動檢測Adapter中的ImageView重用和取消不必要的下載

幫助 

  1. @Override public void getView(int position, View convertView, ViewGroup parent) { 
  2. SquaredImageView view = (SquaredImageView) convertView; 
  3. if (view == null) { 
  4. view = new SquaredImageView(context); 

  5. String url = getItem(position);Picasso.with(context).load(url).into(view); 
  6. }
複製代碼

 


圖片轉換

轉換圖片以適合所顯示的ImageView,來減少內存消耗

幫助 

  1. Picasso.with(context) 
  2. .load(url) 
  3. .resize(50, 50) 
  4. .centerCrop() 
  5. .into(imageView)
複製代碼


還可以設置自定義轉換來實現高級效果,例如下面的矩形特效(把圖片居中裁剪爲矩形)

 

幫助 

  1. public class CropSquareTransformation implements Transformation { 
  2. @Override public Bitmap transform(Bitmap source) { 
  3. int size = Math.min(source.getWidth(), source.getHeight()); 
  4. int x = (source.getWidth() - size) / 2; 
  5. int y = (source.getHeight() - size) / 2; 
  6. Bitmap result = Bitmap.createBitmap(source, x, y, size, size); 
  7. if (result != source) { 
  8. source.recycle(); 

  9. return result; 
  10. }@Override public String key() { return "square()"; } 
  11. }
複製代碼

 


用該類示例調用函數 RequestBuilder.transform(Transformation) 即可。

佔位符圖片

Picasso支持下載和加載錯誤佔位符圖片。

幫助 
Picasso.with(context) 
.load(url) 
.placeholder(R.drawable.user_placeholder) 
.error(R.drawable.user_placeholder_error) 
.into(imageView); 
如果重試3次(下載源代碼可以根據需要修改)還是無法成功加載圖片 則用錯誤佔位符圖片顯示。

支持本地資源加載

從 Resources, assets, files, content providers 加載圖片都支持

Picasso.with(context).load(R.drawable.landing_screen).into(imageView1); 
Picasso.with(context).load(new File("/images/oprah_bees.gif")).into(imageView2); 
調試支持

調用函數 Picasso.setDebug(true) 可以在加載的圖片左上角顯示一個 三角形 ,不同的顏色代表加載的來源

紅色:代表從網絡下載的圖片

黃色:代表從磁盤緩存加載的圖片

綠色:代表從內存中加載的圖片

如果項目中使用了OkHttp庫的話,默認會使用OkHttp來下載圖片。否則使用HttpUrlConnection來下載圖片。

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

其他功能查看項目主頁: http://github.com/square/picasso

參考項目: https://github.com/nostra13/Android-Universal-Image-Loader

https://github.com/mitmel/Android-Image-Cache

https://github.com/novoda/ImageLoader

https://github.com/square/okhttp

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