gradientandroid-jetpack-compose

Jetpack compose gradient image on top of image


I have the below code in xml layout, which I would like to move to compose and havong a hard time to get it right

 <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white">
            <ImageView
                android:id="@+id/image1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:src="@drawable/image"
                app:layout_constraintDimensionRatio="375:258"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <ImageView
                android:id="@+id/image_gradient"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scaleType="fitXY"
                android:src="@drawable/gradient"
                app:layout_constraintBottom_toBottomOf="@id/image1" />
        </androidx.constraintlayout.widget.ConstraintLayout>

I tried in Compose using a Box that didn't work

 Box {
            Image(painter = painterResource(
                id = R.drawable.image1),
                contentDescription = null,
            )

            Image(painter = painterResource(
                id = R.drawable.gradient),
                contentDescription = null,
                contentScale = ContentScale.FillBounds
            )
        }

Solution

  • Most probably your gradient image has zero size.

    You can use Modifier.matchParentSize: it is available in BoxScope. Apply it to the gradient image to make its size equal to the size of the main image.

    Box {
        Image(painter = painterResource(
            id = R.drawable.image1),
            contentDescription = null,
        )
    
        Image(painter = painterResource(
            id = R.drawable.gradient),
            contentDescription = null,
            contentScale = ContentScale.FillBounds,
            modifier = Modifier.matchParentSize()
        )
    }