Search code examples
androidandroid-jetpack-composecoiljetpack-compose-accompanist

Loading local drawables with Coil Compose


I recently migrated from Accompanist's ImagePainter to Coil's, below is the pertinent code after my updates.

val painter = rememberImagePainter(DRAWABLE_RESOURCE_ID)

when (painter.state) {
    is ImagePainter.State.Empty -> Timber.w("Empty")
    is ImagePainter.State.Loading -> {
        Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier.wrapContentSize()
        ) {
            CircularProgressIndicator()
        }
    }
    is ImagePainter.State.Success -> {
        Image(
            painter = painter,
            contentDescription = null,
            contentScale = ContentScale.Fit,
            modifier = Modifier
                .padding(8.dp)
                .size(84.dp)
                .clip(RoundedCornerShape(corner = CornerSize(16.dp)))
        )
    }
    is ImagePainter.State.Error -> Timber.e("Error")
}

Now those images don't render and painter.state is always Empty. My legacy Accompanist implementation displayed images by this point in the code. It also works if I use the stock painterResource(resId) from Compose.

What am I missing to execute Coil's new painter through its states?


Solution

  • As suggested by @Philip Dukhov you don't need coil to load local resources.

    If you want to use it, you can simply your code using:

    val painter = rememberImagePainter(R.drawable.xxx)
    val state = painter.state
    Box(
        contentAlignment = Alignment.Center,
        modifier = Modifier.wrapContentSize()
    ) {
        AnimatedVisibility(visible = (state is ImagePainter.State.Loading)) {
            CircularProgressIndicator()
        }
        Image(
            painter = painter,
            contentDescription = null,
            modifier = Modifier.size(128.dp)
        )
    }
    

    enter image description here