需求又来了:这次我们需要等比例缩放图片至屏幕宽度,这在屏幕上方的广告栏中十分常用。经常我们会用一个固定的高度来摆放广告,但如果需求是高度不固定呢?我尝试了下面的做法(使用Glide从url获取图片)。
Glide.with(activity).load(yourUrl).asBitmap().into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {@Overridepublic void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {int imageWidth = resource.getWidth();int imageHeight = resource.getHeight();int height = ScreenUtils.getScreenWidth() * imageHeight / imageWidth;ViewGroup.LayoutParams para = imageView.getLayoutParams();para.height = height;para.width = ScreenUtils.getScreenWidth();imageView.setImageBitmap(resource);}});
实际上就是先用Glide按图片原始大小加载一次图片,再获取加载的图片宽度和高度及屏幕宽度,计算缩放后的高度再赋值给对应的imageview,最后再把加载得到的图片设置到赋值后的imageview中以完成等比例缩放。在不好获取网络图片的宽高的情况下我选择了上面的方式,如果有更好的方法还请大家分享,谢谢。