為什麼使用Picasso
傳統的加載網絡圖檔。
public void saveToFile(String destUrl) {
FileOutputStream fos = null;
BufferedInputStream bis = null;
HttpURLConnection httpUrl = null;
URL url = null;
int BUFFER_SIZE = ;
byte[] buf = new byte[BUFFER_SIZE];
int size = ;
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)) != -) {
fos.write(buf, , 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的優點
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(, )
.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) / ;
int y = (source.getHeight() - size) / ;
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);
有問題可留言,你的支援我最大的動力