您的位置:首页 > 其它

Picasso 实现图片的比例缩放

2016-05-20 18:03 267 查看
聊天列表中显示图片,这时候需要将整个图片按照设定的最大宽高等比例缩放,才能在看小图的时候把整个图片都显示而不变形。

Picasso提供了这样的方法--实现Transformation

具体实现流程如下:

获取图片的宽高

设定显示的最大的宽高

按源图片宽高比例 计算压缩图片的宽高

根据压缩图片的宽高重新创建新图

具体实现如下:

private class CropSquareTransformation implements Transformation {
@Override
public Bitmap transform(Bitmap source) {

int targetWidth = 目标最大宽度;

int targetHeight = 目标最大高度;

if (source.getWidth() == 0 || source.getHeight() == 0) {
return source;
}

if (source.getWidth() > source.getHeight()) {//横向长图
if (source.getHeight() < targetHeight && source.getWidth() <= 400) {
return source;
} else {
//如果图片大小大于等于设置的高度,则按照设置的高度比例来缩放
double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
int width = (int) (targetHeight * aspectRatio);
if (width > 400) { //对横向长图的宽度 进行二次限制
width = 400;
targetHeight = (int) (width / aspectRatio);// 根据二次限制的宽度,计算最终高度
}
if (width != 0 && targetHeight != 0) {
Bitmap result = Bitmap.createScaledBitmap(source, width, targetHeight, false);
if (result != source) {
// Same bitmap is returned if sizes are the same
source.recycle();
}
return result;
} else {
return source;
}
}
} else {//竖向长图
//如果图片小于设置的宽度,则返回原图
if (source.getWidth() < targetWidth && source.getHeight() <= 600) {
return source;
} else {
//如果图片大小大于等于设置的宽度,则按照设置的宽度比例来缩放
double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
int height = (int) (targetWidth * aspectRatio);
if (height > 600) {//对横向长图的高度进行二次限制
height = 600;
targetWidth = (int) (height / aspectRatio);//根据二次限制的高度,计算最终宽度
}
if (height != 0 && targetWidth != 0) {
Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, height, false);
if (result != source) {
// Same bitmap is returned if sizes are the same
source.recycle();
}
return result;
} else {
return source;
}
}
}
}

@Override
public String key() {
return "desiredWidth" + " desiredHeight";
}
}


使用Picasso加载网络或者本地图片时,进行如下设置:

Picasso.with(context)
.load(url)
.placeholder(R.drawable.default_pic)
.transform(new CropSquareTransformation())
.noFade()
.into(mImgContent);


注意

目标最大宽高可以是ImageView.getWidth() 或者 getHeight().

通过Transformation transformation = new Transformation() {}方式声明transform之后,直接调用
Picasso.with(context)

.load(url)

.transform(new CropSquareTransformation())

.into(mImgContent);
,有异常”Transformation list must not be null”,具体什么原因看源码

Picasso说明书
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: