在Android中,我定义了一个ImageView的layout_width为fill_parent(它占用了手机的全宽度)。

如果我放入ImageView的图像大于layout_width, Android会缩放?那么高度呢?当Android缩放图像时,它会保持纵横比吗?

我发现在ImageView的顶部和底部有一些空白当Android缩放一个比ImageView大的图像时。这是真的吗?如果是,我如何消除空白?


当前回答

当以编程方式执行此操作时,请确保以正确的顺序调用setter:

imageView.setAdjustViewBounds(true)
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP)

其他回答

给其他有这种问题的人。你有一个ImageView,你想要它的宽度为fill_parent,高度按比例缩放:

添加这两个属性到你的ImageView:

android:adjustViewBounds="true"
android:scaleType="centerCrop"

并设置ImageView的宽度为fill_parent,高度为wrap_content。

另外,如果你不想让你的图像被裁剪,试试这个:

 android:adjustViewBounds="true"
 android:layout_centerInParent="true"

看到android: adjustViewBounds。

如果你想让ImageView调整它的边界来保留它的可绘制对象的纵横比,将此设置为true。

快速回答:

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="center"
        android:src="@drawable/yourImage"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

这解决了我的问题

android:adjustViewBounds="true"
android:scaleType="fitXY"

这是它在ConstraintLayout中为我工作的方式:

<ImageView
    android:id="@+id/myImg"
    android:layout_width="300dp"
    android:layout_height="300dp"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true"/>

然后在代码中,我设置drawable为:

ImageView imgView = findViewById(R.id.myImg);
imgView.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.image_to_show, null));

这很好地符合图像的长宽比,并保持它在中心。