【Android】仿朋友圈缩略图展示,根据图片宽高自适应

123 阅读1分钟

1676431643112.png

↑↑公司APP有社区需求,类似朋友圈可以发单张/多张图片,这里只讨论单张图片的实现。
大致需求:用户上传的图片尺寸不定,所以我们不能给imageview设置固定的宽高,且图片不能被拉伸裁剪;并且因为列表中的图片是缩略图,所以图片面积不能过大。

先列出两种错误的实现:
一、给图片设置固定宽度,并通过fitXY和adjustViewbounds实现高度的自适应,这样如果图片是正常尺寸没有问题,但如果是一张长图,就会导致图片过大,pass。

android:layout_width="230dp"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:adjustViewBounds="true"

二、在第一种方案的基础上,宽高自适应,并增加maxWidth、maxHeight,让图片的大小可控:

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:maxHeight="230dp"
android:maxWidth="230dp"

这种方案如果不是放在RecyclerView中是可行的,但是因为RecyclerView的复用机制,导致上下滑动后控件的大小会变化,pass。

最后贴出正确方案,见注释:

ViewGroup.LayoutParams lp = iv.getLayoutParams();
Glide.with(mContext).load(picUrl)
        .listener(new RequestListener<Drawable>() {//监听图片的加载状态,在图片加载进控件前设置宽高
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
            //获取图片宽高
                Double height = (double) resource.getIntrinsicHeight();
                Double width = (double) resource.getIntrinsicWidth();
                //给宽图设置最大宽度,通过原比例设置高度;窄图同理
                if (height > width) {
                    lp.height = ScreenUtils.dp2px(mContext, 230);
                    lp.width = (int) (width / height * lp.height);
                } else {
                    lp.width = ScreenUtils.dp2px(mContext, 230);
                    lp.height = (int) (height / width * lp.width);
                }
                iv.setLayoutParams(lp);
                return false;
            }
        })
        .into(iv);