如何使ImageView的高度与LinearLayout的高度相同,但保持原始纵横比,这会使宽度比LinearLayou



我处于水平LinearLayout(横向应用程序(中。我有一张5000x1080px的图片作为滚动的主屏幕背景。我需要图像填充LinearLayout的高度,同时保持图像的原始比例。这显然会导致宽度与布局的外边缘重叠,因此我将能够用平移来设置它的动画,以实现"平移";滚动";效应

我尝试了scaleType和adjustViewBounds的一系列不同组合,但似乎无法获得所需的效果。ImageView似乎会不断填充高度和宽度,同时保持图像的比例,但不会根据需要使高度与父对象匹配。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="@style/AppTheme.NoActionBar"
android:background="@color/black"
tools:context=".MainActivity">
<ImageView
android:id="@+id/homeBackground"
android:src="@drawable/background_home"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:alpha="0.7"/>

找到了答案:constraintLayout在尺寸上的比例等于图像的尺寸:

<ImageView
android:id="@+id/homeBackground"
android:layout_width="0dp"
android:layout_height="0dp"
android:adjustViewBounds="true"
android:alpha="0.7"
android:src="@drawable/background_home"
app:layout_constraintDimensionRatio="4.629629:1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

由于图像的尺寸为5000x1080,因此得出125:27的比例,然后简化为4.629629:1或(125/27:1(

最新更新