Android中ImageView中无法直接包裹图片

系列文章目录

Android中ImageView中无法直接包裹图片



前言

今天有个以前学校的学弟使用ImageView加载图片时出现了布局空间多余的问题(想动态适配图片的大小),如下图所示。


请添加图片描述

一、先看下XML文件代码

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">


    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/xxxx" />

</RelativeLayout>

二、解决思路

1.没看到代码时的思路

动态获取屏幕宽高,然后设置到图片中。
例:

    DisplayMetrics outMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
    int wPixels = outMetrics.widthPixels;
    int hPixels = outMetrics.heightPixels;
    Log.i(TAG, "wPixels = " + widthPixels + ",hPixels = " + heightPixels);

问题得以解决,但是感觉比较麻烦

2.看到代码后的思路

如果学过Android自定义view的朋友应该很快就能确定是设置为wrap_content的问题。先查看下源码。adjustViewBounds能解决这一问题。

     * @param adjustViewBounds Whether to adjust the bounds of this view
     * to preserve the original aspect ratio of the drawable.  调整此视图的边界以保持绘图的原始宽高比。  
     *
     * @see #getAdjustViewBounds()
     *
     * @attr ref android.R.styleable#ImageView_adjustViewBounds
     */
    @android.view.RemotableViewMethod
    public void setAdjustViewBounds(boolean adjustViewBounds) {
        mAdjustViewBounds = adjustViewBounds;
        if (adjustViewBounds) {
            setScaleType(ScaleType.FIT_CENTER);
        }
    }

且其初始默认值为false

setAdjustViewBounds(a.getBoolean(R.styleable.ImageView_adjustViewBounds, false));

简单的查看一下Android官方文档也发现了此属性。

请添加图片描述

三、解决(时间紧请直接跳转至此)

调用adjustViewBounds,并设置为true即可。

  <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/xxxx"
        android:adjustViewBounds="true" />

希望能解决你的问题。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值