如何在Compose UI Android Jetpack中将url加载到Image到DrawImage中? [英] How do I load url into Image into DrawImage in Compose UI Android Jetpack?

查看:66
本文介绍了如何在Compose UI Android Jetpack中将url加载到Image到DrawImage中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 val image = + imageResource(R.drawable.header)并使用 DrawImage(image)从Drawable Resource中加载图像,

I can use val image = +imageResource(R.drawable.header) and use DrawImage(image) to load image from Drawable Resource,

但是如何将字符串URL加载到 DrawImage(image)中?我尝试使用Glide,但需要将其加载到imageView中.同时, DrawImage(image)不会从imageView接收输入.

But how do I load a string url into the DrawImage(image)?. I've tried using Glide, but it needs to load into imageView. meanwhile DrawImage(image) doesn't take input from imageView.

谢谢.

推荐答案

一种从URL加载位图并使用

A solution loading a Bitmap from the url and using the asImageAsset() Bitmap extension method :

@Composable
fun loadPicture(url: String): UiState<Bitmap> {
    var bitmapState: UiState<Bitmap> by state<UiState<Bitmap>> { UiState.Loading }

    Glide.with(ContextAmbient.current)
        .asBitmap()
        .load(url)
        .into(object : CustomTarget<Bitmap>() {
            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                bitmapState = UiState.Success(resource)
            }

            override fun onLoadCleared(placeholder: Drawable?) { }
        })

    return bitmapState
}

将函数与Image()一起使用,如下所示:

Use the function with your Image() like this :

val loadPictureState = loadPicture(url)
if (loadPictureState is UiState.Success<Bitmap>)
    Image(loadPictureState.data.asImageAsset())
else
    Text("Loading...")

此代码段使用的是 Glide 库和 JetNews Jetpack Compose的Google官方示例

This snippet is using the Glide library and the UiState helper function from the JetNews official Google sample for Jetpack Compose

这篇关于如何在Compose UI Android Jetpack中将url加载到Image到DrawImage中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆