想要加载的图片固定为ImageView的宽度, 高度相应调整, 可以使用Transform:
public static class ImageTransformation {
static Transformation getTransformation(final ImageView imageView) {
return new Transformation() {
@Override
public Bitmap transform(Bitmap source) {
//设置宽度固定为width,如果高度固定宽度自适应同理
int targetWidth = imageView.getWidth();
double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
int targetHeight = (int) (targetWidth * aspectRatio);
Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
if (result != source) {
//如果是同等大小的就回收
source.recycle();
}
return result;
}
@Override
public String key() {
return "transformation" + " desiredWidth";
}
};
}
}
然后加载图片时:
Picasso.get().load(imgUrl).transform(ImageTransformation.getTransformation(imageview))
// .error(R.drawable.default)
// .placeholder(R.drawable.default).
into(imageview);
注意:如果抛出IllegalArgumentException: width and height must be > 0的异常,很可能是因为还没有测量imageview就getWidth()了, 可以用 imageview.post(new Runnable(){})方法 重写run()加载图片。