android:強大的圖片下載和緩存庫Picasso
1.Picasso簡介
Picasso是Square公司出品的一個強大的圖片下載和緩存圖片庫矛绘。官方網(wǎng)址是:http://square.github.io/picasso/
只需要一句代碼就可以將圖片下載并設(shè)置到ImageView上。
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
2.主要特點
2.1Adapter downloads
使用ListView忿等,GridView的時候誊役,自動檢測Adapter的重用(re-use)因块,取消下載革娄,使用緩存捅膘。
@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);
}
2.2圖像處理與變換
將圖像進行變換翘地,以更好的適應(yīng)布局控件等申尤,減小內(nèi)存開銷癌幕。
Picasso.with(context)
.load(url)
.resize(200, 200)
.centerCrop()
.into(imageView)
當然,我們也可以寫自己的變換類昧穿,但是必須實現(xiàn)Transformation接口勺远,如:
/**
* 自定義接口,實現(xiàn)圖像縮小為原來的一半
*/
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()";
}
}
然后設(shè)置transform方法就可以了:
Picasso.with(this).load("http://i.imgur.com/DvpvklR.png")
.transform(new CropSquareTransformation()).into(iv_test2);
效果圖如下:
2.3时鸵。支持設(shè)置加載之前的圖片胶逢,和加載失敗后的圖片。
如:<?喎?"/kf/ware/vc/" target="_blank" class="keylink">vcD48cD48cHJlIGNsYXNzPQ=="brush:java;">Picasso.with(this) .load("http://i.imgur.com/DvpvklR.png") .placeholder(R.drawable.abc) .error(R.drawable.ic_launcher) .transform(new CropSquareTransformation()) .into(iv_test1);
ImageView創(chuàng)建時顯示abc.png,如果加載成功饰潜,顯示的是DvpvklR.png初坠,如果加載失敗,顯示ic_launcher.png.
2.4支持加載本地圖片和sdcard中的圖片文件等彭雾。
Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
Picasso.with(context).load(new File(...)).into(imageView2);