相比较其他,picasso的图片缓存更加简单一些,他只需要一行代码就可以表述:导入相关jar包
Picasso.with(context).load("图片路径").into(ImageView控件);
listView加载图片,在现在的app中都是非常常见的,我们往往要处理图片加载缓慢,错位等常见问题。Picasso不仅实现了图片的异步加载,同时对一些问题也做了解决和优化
比如:1.当在listView,滑动的时候,我们需要在adapter中把已经不再视野的ImageView图片资源进行回收,否则会出现图片错位。
2.将图片压缩转换,减少内存消耗,
@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);
Picasso. // 创建Picasso对象 with(context). // 载入Url,此方法有很多重载,可自行尝试 load(url). //读取本地文件不缓存 memoryPolicy(MemoryPolicy.NO_CACHE). //读取网络文件不缓存 networkPolicy(NetworkPolicy.NO_CACHE). //图片显示之前的占位图片 placeholder(R.drawable.drawer_avatar_default). //重新设置宽高, 此处使用了从Dimen文件获取, 推荐这种方式,也可以直接设置PX值 resize(context.getResources().getDimensionPixelSize(R.dimen.space_64dp), context.getResources().getDimensionPixelSize(R.dimen.space_64dp)). //按照上一步重置的宽高居中显示 centerCrop(). //使用自定义变换, 此处是圆形头像效果 transform(new CircleTransformation()). //不淡入淡出, 直接显示 noFade(). //目标ImageView into(target);
自定义圆形的转换类
public class CircleTransformation implements Transformation { private static final int STROKE_WIDTH = 6; @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 squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); if (squaredBitmap != source) { source.recycle(); } Bitmap bitmap = Bitmap.createBitmap(size, size,source.getConfig()); Canvas canvas = new Canvas(bitmap); Paint avatarPaint = new Paint(); BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); avatarPaint.setShader(shader); Paint outlinePaint = new Paint(); outlinePaint.setColor(Color.WHITE); outlinePaint.setStyle(Paint.Style.STROKE); outlinePaint.setStrokeWidth(STROKE_WIDTH); outlinePaint.setAntiAlias(true); float r = size / 2f; canvas.drawCircle(r, r, r, avatarPaint); canvas.drawCircle(r, r, r - STROKE_WIDTH / 2, outlinePaint); squaredBitmap.recycle(); return bitmap; } @Override public String key() { return "circleTransformation()"; }