【问题标题】:How to make an ImageView the same height as the LinearLayout, but keep original aspect ratio which makes the width wider than the LinearLayout如何使 ImageView 与 LinearLayout 具有相同的高度,但保持原始纵横比使宽度比 LinearLayout 更宽
【发布时间】:2022-08-18 21:15:01
【问题描述】:

我在一个水平的 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\"/>
  • 在发布此内容之前,您是否阅读了质量建议?请参阅:How do I avoid misusing tags?
  • 当我在开发中使用 Android Studio 时,我不确定为什么要删除 Android-Studio 标签。
  • 该标签仅适用于有关工具本身的问题,不适用于一般的 Android 开发问题。在您提交此问题之前,您应该已被告知该事实。你看过通知吗?
  • 好吧,有道理,误会请见谅。

标签: android xml kotlin android-linearlayout android-imageview


【解决方案1】:

找到了答案:在尺寸上的约束布局,其比率等于图像的尺寸:

<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)

【讨论】:

    猜你喜欢
    • 2021-06-23
    • 2012-06-05
    • 1970-01-01
    • 2016-04-01
    • 2014-07-01
    • 2021-11-02
    • 1970-01-01
    • 2016-01-17
    • 2018-06-21
    相关资源
    最近更新 更多