原創地址:http://mcode114.com/android/network/picasso/
-
類別:網絡
-
開發環境:Android Studio
Picasso
Picasso是Square公司開源的一個Android圖形緩存庫。可以實現圖片下載和緩存功能。僅僅只需要一行代碼就能完全實現圖片的異步加載。使用複雜的圖片轉換技術降低內存的使用。在adapter中需要取消已經不在視野範圍的ImageView圖片資源的加載。
用法
通過配置gradle配置將Picasso框架引入項目。
compile'com.squareup.picasso:picasso:2.5.2'
除了加載網絡圖片picasso還支持加載Resources, assets, files, content providers中的資源文件。
//加載網絡圖片
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView1);
//加載Resources資源
Picasso.with(context).load(R.drawable.landing_screen).into(imageView2);
//加載assets資源
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView3);
//加載files資源
Picasso.with(context).load(newFile(...)).into(imageView4);
Picasso能自動檢測到Adapter的重用,會取消上次的加載
@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(50,50)
.centerCrop()
.into(imageView)
你還可以指定更高級效果的自定義轉換。
publicclass CropSquareTransformation implementsTransformation {
@Override
publicBitmap transform(Bitmap source) {
intsize = Math.min(source.getWidth(), source.getHeight());
intx = (source.getWidth() - size) /2;
inty = (source.getHeight() - size) /2;
Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
if(result != source) {
source.recycle();
}
returnresult;
}
@Overridepublic String key() { return"square()"; }
}
Picasso支持加載過程中和加載錯誤時顯示對應圖片
Picasso.with(context)
.load(url)
//加載過程中的圖片顯示
.placeholder(R.drawable.user_placeholder)
//加載失敗中的圖片顯示
//如果重試3次(下載源代碼可以根據需要修改)還是無法成功加載圖片,則用錯誤佔位符圖片顯示。
.error(R.drawable.user_placeholder_error)
.into(imageView);
默認情況下,Android使用ARGB_8888設置圖片質量
Picasso.with( imageView.getContext() )
.load(url)
.config(Bitmap.Config.RGB_565)
.into(imageView);
ALPHA_8:每個像素佔用1byte內存Android中有四種,分別是:
-
ARGB_4444:每個像素佔用2byte內存
-
ARGB_8888:每個像素佔用4byte內存
-
RGB_565:每個像素佔用2byte內存
在開發階段,我們可以通過調用setIndicatorsEnabled(true)方法,設置Picasso可以根據圖片來源的不同在圖片上做出不同顏色的標記。