使用Transformation代替fit、resize
一开始使用下面代码加载图片,发现图片显示不出来
Picasso.with(context)
.load(new File(data.content))
.placeholder(R.drawable.default_publishlist)
.fit()
.centerInside()
.into(binding.ivContent);
后来去掉fit、centerInside方法,图片可以加载出来,不过占用内存非常大,显然还是存在问题。经过探索发现Picasso有一个Transformation接口,可以自定义转换图像,于是有了的处理方式:
Picasso.with(context)
.load(new File(data.content))
.placeholder(R.drawable.default_publishlist)
.transform(getTransformation(binding.ivContent))
.into(binding.ivContent);
private static Transformation getTransformation(final ImageView view) {
return new Transformation() {
@Override
public Bitmap transform(Bitmap source) {
int targetWidth = view.getWidth();
//返回原图
if (source.getWidth() == || source.getWidth() < targetWidth) {
return source;
}
//如果图片大小大于等于设置的宽度,则按照设置的宽度比例来缩放
double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
int targetHeight = (int) (targetWidth * aspectRatio);
if (targetHeight == || targetWidth == ) {
return source;
}
Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
if (result != source) {
// Same bitmap is returned if sizes are the same
source.recycle();
}
return result;
}
@Override
public String key() {
return "transformation" + " desiredWidth";
}
};
}
根据ImageView宽高来计算加载图片的大小,可以大大节省占用的内存,避免发生OOM