考虑以下布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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.support.constraint.ConstraintLayout
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#0000FF"
android:padding="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintDimensionRatio="H,3:1"
tools:layout_editor_absoluteX="16dp" />
</android.support.constraint.ConstraintLayout>
</RelativeLayout>
我不确定 app:layout_constraintDimensionRatio 是如何工作的。我的理解是比例永远是宽度:高度。所以 3:1 总是会让 ImageView 看起来比高度宽 3 倍。前缀 H 或 W 告诉 ConstraintLayout 哪个维度应该遵守比率。如果是 H 则意味着首先从其他约束计算宽度,然后根据纵横比调整高度。然而,这是布局的结果:
高度是宽度的 3 倍,这是出乎意料的。谁能向我解释如何根据 app:layout_constraintDimensionRatio 设置计算尺寸?
原文由 darklord 发布,翻译遵循 CC BY-SA 4.0 许可协议
您对
app:layout_constraintDimensionRatio
工作方式的理解是正确的。如果你设置了app:layout_constraintDimensionRatio="H,3:1"
那么这意味着宽度将首先从其他约束中计算出来,然后高度将根据纵横比进行调整。您的实现的唯一问题是您将app:layout_constraintBottom_toBottomOf="parent"
添加到 ImageView 中,从而导致app:layout_constraintDimensionRatio
被忽略。这是以 3:1 纵横比调整 ImageView 大小的布局:
这是结果视图: