爲什麼使用Picasso
傳統的加載網絡圖片。
public void saveToFile(String destUrl) {
FileOutputStream fos = null;
BufferedInputStream bis = null;
HttpURLConnection httpUrl = null;
URL url = null;
int BUFFER_SIZE = 1024;
byte[] buf = new byte[BUFFER_SIZE];
int size = 0;
try {
url = new URL(destUrl);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
fos = new FileOutputStream("c:\\haha.gif");
while ((size = bis.read(buf)) != -1) {
fos.write(buf, 0, size);
}
fos.flush();
} catch (IOException e) {
} catch (ClassCastException e) {
} finally {
try {
fos.close();
bis.close();
httpUrl.disconnect();
} catch (IOException e) {
} catch (NullPointerException e) {
}
}
}
@Override
public CharSequence getAccessibilityClassName() {
return CheckBox.class.getName();
}
使用Picasso加載
Picasso.with(context).load("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2812025359,799095506&fm=23&gp=0.jpg").into(imageView);
Picasso的優點
Picasso可以自動處理Android上圖像加載的許多常見缺陷:
- 處理ImageView回收和下載取消在適配器
- 複雜的圖像轉換與最小的內存使用
- 自動內存和磁盤緩存。
自動檢測適配器重新使用,並取消以前的下載。
@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)
您還可以爲更高級的效果指定自定義轉換。
然後將此類的實例傳遞給transform方法。
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(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/jian.png").into(imageView2);
Picasso.with(context).load(new File(...)).into(imageView3);
有問題可留言,你的支持我最大的動力