Home > Back-end >  How to modify color and size for Coil image placeholder in Jetpack Compose
How to modify color and size for Coil image placeholder in Jetpack Compose

Time:10-05

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related