45

Well, I am studying the Compose UI and I am stucking in basic things. One of them is show a image from URL with Glide.

I have tried the below code but the delegates (onResourceReady and onLoadCleared) are not being called.

Did I miss something?

@Composable
fun loadPicture(url: String, contentDescription:String, modifier: Modifier = Modifier) {

  val bitmapState = remember { mutableStateOf<Bitmap?>(null) }
  Glide.with(LocalContext.current).asBitmap().load(url).into(
    object : CustomTarget<Bitmap>() {
        override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
            bitmapState.value = resource
        }
        override fun onLoadCleared(placeholder: Drawable?) {}
    }
)

  bitmapState.value?.let {
    Image(
        contentDescription = contentDescription,
        bitmap = it.asImageBitmap(),
        modifier = modifier
    )
  }
}
1
  • See coil-kt.github.io/coil/compose. Add implementation("io.coil-kt:coil-compose:2.5.0") to a corresponding build.gradle file and use AsyncImage.
    – CoolMind
    Commented Nov 20, 2023 at 19:56

1 Answer 1

100

You can use Coil for compose:

Add the dependency:

implementation("io.coil-kt:coil-compose:2.0.0-rc01")

and use it like this:

Image(
    painter = rememberAsyncImagePainter("https://www.example.com/image.jpg"),
    contentDescription = null,
    modifier = Modifier.size(128.dp)
)
3
  • Hi, do you have any suggestions on how to have Image resize automatically based on the size of the asset? Like, say we don't know the dimensions of the remote image before we download it.
    – Eugene
    Commented Aug 19, 2021 at 4:35
  • @Eugene just don't pass modifier with defined size.
    – goofy
    Commented Aug 19, 2021 at 12:02
  • I tried this, but I didn't have much luck unfortunately. I posted a SO question, can you take a look if you have time? stackoverflow.com/q/68848663/2852849
    – Eugene
    Commented Aug 19, 2021 at 13:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.