如何使用Jetpack Compose在Android中添加图片

10

我正在尝试使用Android Jetpack Compose将图像添加到活动中,但它出现了错误:

import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Image


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Image(bitmap = imageFromResource(res = resources, resId =R.drawable.ic_launcher_background))
        }
    }
}


This is the screenshot of Android Studio

3个回答

9

大多数本地图片加载的情况可以使用 Image 中的 painterResource 来完成。

例如:

Image(painter = painterResource(id = R.drawable.ic_launcher_background), contentDescription = "")

如果您想改变图像资产的颜色,那么请使用带有 painterResource 的图标。

Icon(painter = painterResource(id = R.drawable.ic_launcher_background), contentDescription = "", tint = Color.Red)

如果您想从远程URL加载,则使用Coil

添加依赖项:

implementation "dev.chrisbanes.accompanist:accompanist-coil:0.6.1"

然后像下面这样使用它:

 CoilImage(
                data = "https://www.instaily.com/images/android.jpg",
                contentDescription = "android",
                alignment = Alignment.TopCenter,
                modifier = Modifier
                    .fillMaxWidth()
                    .fillMaxHeight(.60f),
                contentScale = ContentScale.Crop,
                loading = {
                    Box(
                        modifier = Modifier.background(
                            shape = RoundedCornerShape(20.dp),
                            color = Teal200
                        )
                    )
                },
                error = {
                    Box(
                        modifier = Modifier.background(
                            shape = RoundedCornerShape(20.dp),
                            color = Teal200
                        )
                    )
                }
            )

5

这两者都可以用来获取图片资源。

使用 painterResource API 来加载矢量图形或像 PNG 这样的光栅化资产格式。您不需要知道可绘制对象的类型,只需使用 painterResource 即可。

import androidx.compose.ui.res.painterResource

        Image(painterResource(id = imageResource), contentDescription = contentDescription)

或者

import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.res.imageResource

        Image(ImageBitmap.imageResource(id = imageResource), contentDescription = contentDescription)

或者

import androidx.compose.ui.res.vectorResource

        Image(ImageVector.vectorResource(id = imageResource), contentDescription = contentDescription)

2
这是该问题的另一种可行代码解决方案:

代码:

     Image(
          painter = painterResource(R.drawable.happy_meal_small),
          contentDescription = null
      )

输出:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接