Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load image from URL in Jetpack Compose? [duplicate]

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
    )
  }
}
like image 534
LMaker Avatar asked Apr 05 '21 18:04

LMaker


People also ask

How do you load a drawable image in jetpack compose?

To work with images in Jetpack Compose we will use Image Composable, which contains differnt properties to load images from drawable folder, load bitmaps and also we can load images from network or Url. ImageView is also commonly used to apply tints to an image and handle image scaling.

What is LazyColumn in jetpack compose?

A LazyColumn is a vertically scrolling list that only composes and lays out the currently visible items. It's similar to a Recyclerview in the classic Android View system.

What is Mutablestateof in jetpack compose?

If you want to change the state of TextField and also update the UI, you can use a MutableState . Compose observes any reads and writes to the MutableState object and triggers a recomposition to update the UI.

Does jetpack compose have hot reload?

Right now, compose does not support Hot reloads. But Literals values can be updated directly.


Video Answer


1 Answers

You can use Coil for compose:

  • https://coil-kt.github.io/coil/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)
)
like image 106
nglauber Avatar answered Oct 06 '22 22:10

nglauber