Glide加载时等比例缩放图片至屏幕宽度(通过加载下来的图片动态设置)

首先我们需要吧图片的控件修改为全屏尺寸

  <ImageView
            android:id="@+id/iv_thumb1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:src="@drawable/ic_tiktok_shu"
            android:visibility="visible" />

然后就是代码设置宽高

Glide.with(activity).load(StrUrl).asBitmap().into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                    @Override
                    public 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);
                    }
                });

这里说下如果需要可以设置图片裁剪的方式

.centerCrop()//设置图片加载居中裁剪

原理:先用Glide按图片原始大小加载一次图片,再获取加载的图片宽度和高度及屏幕宽度,计算缩放后的高度再赋值给对应的imageview,最后再把加载得到的图片设置到赋值后的imageview中以完成等比例缩放

 

by leileitua

posted @ 2020-07-30 17:34  WidgetBox  阅读(5233)  评论(0编辑  收藏  举报