我想知道是否可以使用 Constraintlayout 实现以下目标:
我有一个固定比例 (2:1) 的图像,并希望它用渐变叠加,渐变应该从图像的底部开始,然后将其顶部对齐到图像高度的 50%。
据我所知,这是不可能的。
使用 Guideline 不起作用,因为它只能放置在 Percentage to the Parent/Layout
使用 weight
只能在 Chains 中使用,但是因为我需要覆盖两个 View 链,所以不能使用,对吗?
最佳答案
你可以像下面这样实现:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
<ImageView
android:id="@+id/imageView4"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintDimensionRatio="2:1"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@android:color/darker_gray" />
<View
android:id="@+id/View_Top"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintDimensionRatio="4:1"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@android:color/transparent" />
<View
android:id="@+id/View_Bottom"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintDimensionRatio="4:1"
app:layout_constraintTop_toBottomOf="@id/View_Top"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@android:color/holo_orange_dark" />
</android.support.constraint.ConstraintLayout>
此处 imageView 设置为 2:1 比例,并在上面的 Imageview 中设置了 2 个额外 View ,其中 View_Top 是透明的,View_Bottom 是 imageview 的下半部分,因此您可以在 View_Bottom 中设置渐变。
下图中背景颜色为灰色,您的颜色可以替换为 View_Bottom 颜色
关于android - ConstraintLayout 使 View 高度 x sibling 的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49514205/