Android圖片加載庫:Picasso詳解

Picasso 其實是 Android 系統的圖片下載和緩存類庫,是Square開源的一個用於Android系統下載和緩存圖片的項目。下面我們就來講講在Android開發中,Picasso有哪些特性及如何使用。

Picasso的特性

1、處理Adapter中的 ImageView 回收和取消已經回收ImageView的下載進程

示例代碼:

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);
}

2、使用最少的內存完成複雜的圖片轉換,比如把下載的圖片轉換爲圓角。

示例代碼:

Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.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);


4、支持調試

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

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

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

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

5、支持下載和加載錯誤佔位符圖片

Picasso.with(context)
.load(url)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);

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

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()"; }
}

Picasso的使用

直接說,有點空,且不易明白,舉個例子說明吧:

Picasso.with(context).load("http://www.maiziedu.com/uploads/course/2015/07/android_studio.jpg");


主要功能

        // with():初始化;
// load():下載圖片;
// centerCrop():將圖片放大到:大於等於ImageView的寬高.
// error():設置圖片下載時候的默認顯示圖片;
// placeholder():設置圖片下載過程中顯示的圖片.
// priority():設置圖片下載任務的優先級;
// resize():設置圖片的尺寸;
// rotate():設置圖片的旋轉角度;
// into():展示圖片.


感謝:

http://blog.csdn.net/bear_huangzhen/article/details/45868755

http://zxs19861202.iteye.com/blog/1989032


picasso項目主頁:

https://github.com/square/picasso


注:這裏有一篇講Picasso與Glide區別的博客,強烈推薦。

http://blog.csdn.net/fancylovejava/article/details/44747759



發佈了30 篇原創文章 · 獲贊 19 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章