Android开发必备之Picasso加载图片

来源:互联网 发布:南京医科大学数据库 编辑:程序博客网 时间:2024/06/06 00:41

为什么使用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上图像加载的许多常见缺陷:

  1. 处理ImageView回收和下载取消在适配器
  2. 复杂的图像转换与最小的内存使用
  3. 自动内存和磁盘缓存。

自动检测适配器重新使用,并取消以前的下载。

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

有问题可留言,你的支持我最大的动力

2 0
原创粉丝点击