Issue
How to set a drawable resource as a background to an Image
in Jetpack compose?
Corresponding view XML code
<androidx.appcompat.widget.AppCompatImageView
android:background="@drawable/drawable_black_circle"
android:src="@drawable/app_logo"
...
/>
My current code,
Image(
painter = painterResource(id = R.drawable.app_logo),
contentDescription = null,
modifier = Modifier
.height(160.dp)
.width(160.dp)
.padding(32.dp),
)
Modifier.background()
gives me the option to use color as a background.
Similarly looking for a way to use a drawable resource as a background.
Note:
Looking for a way to have the background in the image.
Not looking for enclosing the image inside another composable with the background.
Solution
With Jetpack compose, it is easy to draw a circle background or any shapes by using shape Solution 1:
Image(painterResource(id = R.drawable.avatar1), contentDescription = null,
modifier = Modifier.size(160.dp).background(
color = Color.Black,
shape = CircleShape
)
)
Solution 2: In the case, you want to use a background image, you can use :
Modifier.paint
For your case:
Image(
painter = painterResource(id = R.drawable.app_logo),
contentDescription = null,
modifier = Modifier
.height(160.dp)
.width(160.dp)
.paint(
painter = painterResource(R.drawable.drawable_black_circle),
contentScale = ContentScale.FillWidth
)
.padding(32.dp),
)
For other layouts, we can do the same. Here is an example for ConstraintLayout
ConstraintLayout(
modifier = Modifier
.fillMaxWidth()
.paint(painterResource(id = R.drawable.ic_background_detail), contentScale = ContentScale.FillWidth)
) {
}
Answered By - NhatVM
Answer Checked By - Mary Flores (JavaFixing Volunteer)