在作android图片加载的时候,因为手机屏幕受限,不少大图加载过来的时候,咱们要求等比例缩放,好比按照固定的宽度,等比例缩放高度,使得图片的尺寸比例获得相应的缩放,但图片没有变形。显然按照android:scaleType不能实现,由于会有不少限制,因此必需要本身写算法。 android
经过Picasso来缩放
其实picasso提供了这样的方法。具体是显示Transformation 的 transform 方法。
(1) 先获取网络或本地图片的宽高
(2) 获取须要的目标宽
(3) 按比例获得目标的高度
(4) 按照目标的宽高建立新图算法
Transformation transformation = new Transformation() { @Override public Bitmap transform(Bitmap source) { int targetWidth = mImg.getWidth(); LogCat.i("source.getHeight()="+source.getHeight()); LogCat.i("source.getWidth()="+source.getWidth()); LogCat.i("targetWidth="+targetWidth); if(source.getWidth()==0){ return source; } //若是图片小于设置的宽度,则返回原图 if(source.getWidth()<targetWidth){ return source; }else{ //若是图片大小大于等于设置的宽度,则按照设置的宽度比例来缩放 double aspectRatio = (double) source.getHeight() / (double) source.getWidth(); int targetHeight = (int) (targetWidth * aspectRatio); if (targetHeight != 0 && targetWidth != 0) { Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, 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 "transformation" + " desiredWidth"; } };
以后在Picasso设置transform网络
Picasso.with(mContext)
.load(imageUrl)
.placeholder(R.mipmap.zhanwei)
.error(R.mipmap.zhanwei)
.transform(transformation)
.into(viewHolder.mImageView);
Transformation 这是Picasso的一个很是强大的功能了,它容许你在load图片 -> into ImageView 中间这个过成对图片作一系列的变换。好比你要作图片高斯模糊、添加圆角、作度灰处理、圆形图片等等均可以经过Transformation来完成。
参考文章: https://stackoverflow.com/questions/21889735/resize-image-to-full-width-and-variable-height-with-picassoide