Android,根据宽度,自动缩放高度

本文介绍了一种在不同屏幕尺寸下保持图片宽高比,同时实现图片宽度铺满屏幕,高度自动缩放的方法。通过调整ImageView属性和使用代码监听布局变化,确保了图片在平板等大屏幕设备上的美观展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中有一个需求,就是展示图片宽度铺满,但是高度是要自动缩放的。 来上一个最普通的代码:

<ImageView
  android:id="@+id/img_background"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:src="@mipmap/qr1"
  android:scaleType="centerCrop"/>

在平板上,大屏幕尺寸的效果是这样

这里写图片描述

这么丑,怎么可以忍?真实的效果应该要这样的:

这里写图片描述

好了,下面说下怎么做的。

1、加上android:adjustViewBounds=”true”,它的作用是保持宽高比。

<ImageView
            android:id="@+id/img_background"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            android:adjustViewBounds="true"
            android:src="@mipmap/qr1" />

2、代码

ViewTreeObserver vto = img_background.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                img_background.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                DisplayMetrics dm = new DisplayMetrics();
                wm.getDefaultDisplay().getMetrics(dm);
                int width = dm.widthPixels;         // 屏幕宽度(像素)
                int height = dm.heightPixels;       // 屏幕高度(像素)
                int screenWidth =width; // 获取屏幕宽度
                ViewGroup.LayoutParams lp = img_background.getLayoutParams();
                lp.width = screenWidth;
                lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                img_background.setLayoutParams(lp);
                img_background.setMaxWidth(screenWidth);
                img_background.setMaxHeight(screenWidth * 5); 
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值