Picasso的基本使用

来源:互联网 发布:网络词汇大全 编辑:程序博客网 时间:2024/06/06 00:30

Picasso的基本使用

picasso仅需一行代码就能实现图片的异步加载

Picasso.with(context).load("网址url").into(imageView);

Picasso不仅实现了图片异步加载的功能,还解决了android中加载图片时需要解决的一些常见问题:

  1. 在adapter中需要取消已经不在视野范围的ImageView图片资源的加载,否则会导致图片错位,Picasso已经解决了这个问题。
  2. 使用复杂的图片压缩转换来尽可能的减少内存消耗
  3. 自带内存和硬盘二级缓存功能

Picasso特性

ADAPTER 中的下载:Adapter的重用会被自动检测到,Picasso会取消上次的加载

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

也可以自定义转换(需要继承Transformation):

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()"; }}

注:将CropSquareTransformation 的对象传递给transform 方法即可。

Place holders-空白或者错误占位图片

picasso提供了两种占位图片,未加载完成或者加载发生错误的时需要一张图片作为提示。

Picasso.with(context).load(url).placeholder(R.drawable.user_placeholder)//没有加载图片时显示的默认图像.error(R.drawable.user_placeholder_error)// 图像加载错误时显示的图像.into(imageView);// 被加载的控件

注:如果加载发生错误会重复三次请求,三次都失败才会显示erro Place holder。

资源文件的加载

除了加载网络图片以外,picasso还支持加载Resources, assets, files, content providers中的资源文件。

Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);Picasso.with(context).load(new File(...)).into(imageView3);
0 0