1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Android 使用Picasso加载网络图片等比例缩放

Android 使用Picasso加载网络图片等比例缩放

时间:2024-02-19 16:50:13

相关推荐

Android 使用Picasso加载网络图片等比例缩放

在做android图片加载的时候,由于手机屏幕受限,很多大图加载过来的时候,我们要求等比例缩放,比如按照固定的宽度,等比例缩放高度,使得图片的尺寸比例得到相应的缩放,但图片没有变形。显然按照android:scaleType不能实现,因为会有很多限制,所以必须要自己写算法。

通过Picasso来缩放

其实picasso提供了这样的方法。具体是显示Transformation 的 transform 方法。

(1) 先获取网络或本地图片的宽高

(2) 获取需要的目标宽

(3) 按比例得到目标的高度

(4) 按照目标的宽高创建新图

Transformation transformation = new Transformation() {@Overridepublic 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 samesource.recycle();}return result;} else {return source;}}}@Overridepublic 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来完成。

参考文章:/questions/21889735/resize-image-to-full-width-and-variable-height-with-picasso

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。