How to modify color and size for Coil image placeholder in Jetpack Compose

3.9k views Asked by At

I'm using Coil 1.3.2 in Jetpack Compose and I have an Image like this

Image(
    painter = rememberImagePainter(
        data = imageUrl,
        onExecute = { _, _ -> true },
        builder = {
            placeholder(R.drawable.icon)
        }
    ),
    contentScale = ContentScale.FillWidth,
    contentDescription = null,
    modifier = Modifier
        .fillMaxWidth()
        .aspectRatio(1f)
)

How can I set a custom color and size for my placeholder icon ?
I didn't find any examples on the documentation

3

There are 3 answers

0
Phil Dukhov On BEST ANSWER

You can use painter.state to see if the image is still loading, and use Box to display the desired placeholder. Note that the Image to be loaded must be in the view hierarchy, just defining rememberImagePainter won't start loading.

You can use either Image or Icon for the placeholder: if you need to change tint color, the second option seems cleaner:

Box(contentAlignment = Alignment.Center) {
    val painter = rememberImagePainter(data = imageUrl)
    Image(
        painter = painter,
        contentScale = ContentScale.FillWidth,
        contentDescription = null,
        modifier = Modifier
            .fillMaxWidth()
            .aspectRatio(1f)
    )
    if (painter.state !is ImagePainter.State.Success) {
        Icon(
            painter = painterResource(id = R.drawable.icon),
            contentDescription = null,
            tint = Color.Blue,
            modifier = Modifier.size(100.dp)
        )
    }
}

I'm using contentAlignment = Alignment.Center to center static size placeholder inside the Box, also you can add Modifier.matchParentSize() to the placeholder so it'll be the same size as the image, use fillMaxSize(part) to take part of parent space, etc.

Also you can use AnimatedVisibility instead of if to add an animation.

0
Jakoss On

AFAIK you cannot do that using the resource directly, but you could use different placeholder overload taking the Drawable object. You could try and do what you need directly in that object

0
heyshowshana On

I find it much easier to use the Box {...} component and add the Image/Placeholder composable underneath the AsyncImage.

Like this:

Box {
    PlaceholderComposable()
    AsyncImage(
        model = url,
        contentDescription = null,
        ...
    )
}

But of course - both the image and the composable should have their modifiers set up correctly - so that they cover each other.

I am using Coil 2.4.0.