如何在Jetpack compose中从drawable加载图像?

问题描述 投票:0回答:13

我已经尝试过下面的代码,但它在用户界面中没有反映任何内容,我在这里遗漏了任何东西?

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            loadUi()
        }
    }

    @Composable
    fun loadUi() {
        CraneWrapper {
            MaterialTheme {
                Image(
                    (ResourcesCompat.getDrawable(
                        resources,
                        R.mipmap.ic_launcher,
                        null
                    ) as BitmapDrawable).bitmap
                )
            }
        }
    }
}
android image androidx android-jetpack-compose
13个回答
155
投票

您可以使用

painterResource
功能:

 Image(painterResource(R.drawable.ic_xxxx),"content description")

具有给定 ID 的资源必须指向完全光栅化的 images(例如 PNG 或 JPG 文件)或

VectorDrawable
xml 资源。
这意味着此方法可以分别为基于
BitmapPainter
的资产或基于矢量的资产加载
VectorPainter
ImageBitmap
的实例。

示例:

Card(
    modifier = Modifier.size(48.dp).tag("circle"),
    shape = CircleShape,
    elevation = 2.dp
) {
    Image(
        painterResource(R.drawable.ic_xxxx),
        contentDescription = "",
        contentScale = ContentScale.Crop,
        modifier = Modifier.fillMaxSize()
    )
}


32
投票

从版本

1.0.0-beta01
开始:

Image(
    painter = painterResource(R.drawable.your_drawable),
    contentDescription = "Content description for visually impaired"
)

12
投票

尝试这个,但如果你复制代码然后粘贴它,我不知道为什么,但它不起作用,所以只需按原样输入它并替换图像 ID

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

8
投票

由于

imageResource
不再可用,带有
painterResource
的解决方案确实是正确的,例如

Image(painter = painterResource(R.drawable.ic_heart), contentDescription = "content description")

但如果你需要的话,你实际上仍然可以使用 Bitmap 而不是可绘制的:

Image(bitmap = bitmap.asImageBitmap())

.asImageBitmap()
是 compose 提供的 Bitmap 扩展,它从给定的 Bitmap 创建一个 ImageBitmap。


7
投票

工作于

0.1.0-dev14

在图像中加载可绘制对象可以通过以下方式实现:

Image(
      imageResource(id = R.drawable.scene_01),
      modifier = Modifier.preferredHeightIn(160.dp, 260.dp)
                    .fillMaxWidth(),
      contentScale = ContentScale.Crop
   )

现在,我正在尝试在 Circle Image 中上传可绘制对象,这听起来很棘手,但在 JetPack Compose 中却太简单了。你可以通过这种方式实现:

Image(
         asset = imageResource(id = R.drawable.scene_01),
         modifier = Modifier.drawBackground(
                    color = Color.Black,
                    style = Stroke(4f),
                    shape = CircleShape
          ).preferredSize(120.dp)
                    .gravity(Alignment.CenterHorizontally)
                    .clip(CircleShape),
          contentScale = ContentScale.FillHeight
      )

输出:


4
投票

版本=1.0.0-beta01,使用

painterResource
imageResource
已删除。

示例

Image(
    painterResource(R.drawable.ic_vector_or_png),
    contentDescription = null,
    modifier = Modifier.requiredSize(50.dp)
)

android 开发文档


3
投票

版本为1.0.0-beta01

就像下面这样

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

2
投票
@Composable
fun loadUi() {
val image = +imageResource(R.drawable.header)
    CraneWrapper {
        MaterialTheme {
            Container(expanded = true,height = 180.dp) {
                //Use the Clip() function to round the corners of the image
                Clip(shape = RoundedCornerShape(8.dp)) {
                //call DrawImage() to add the graphic to the app
                    DrawImage(image)
                }
            }
        }
    }
}

1
投票

我发现AndroidImage.kt中有一个函数imageFromResource()

fun imageFromResource(res: Resources, resId: Int): Image {
    return AndroidImage(BitmapFactory.decodeResource(res, resId))
}

所以你的代码是:

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        loadUi()
    }
}

@Composable
fun loadUi() {
    CraneWrapper {
        MaterialTheme {
            val image = imageFromResource(resources, R.mipmap.ic_launcher)
            SimpleImage(image)
        }
    }
}

}


0
投票

我从jetpack compose库中找到了SimpleImage类来加载图像,但这是一个临时解决方案,我还没有找到任何样式选项。

// TODO(Andrey) Temporary. Should be replaced with our proper Image component when it available
@Composable
fun SimpleImage(
    image: Image
) {
    // TODO b132071873: WithDensity should be able to use the DSL syntax
    WithDensity(block = {
        Container(width = image.width.toDp(), height = image.height.toDp()) {
            Draw { canvas, _ ->
                canvas.drawImage(image, Offset.zero, Paint())
            }
        }
    })
}

我就是这样用的

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            loadUi()
        }
    }

    @Composable
    fun loadUi() {
        CraneWrapper {
            MaterialTheme {
                val bitmap = (ResourcesCompat.getDrawable(
                        resources,
                        R.mipmap.ic_launcher,
                        null
                    ) as BitmapDrawable).bitmap
                SimpleImage(Image(bitmap))
            }
        }
    }
}

不过,我不确定这是从可绘制对象加载图像的正确方法。


0
投票

如果您有

Drawable
实例,您可以使用 Accompanist Drawable Painter:

https://google.github.io/accompanist/drawablepainter/

dependencies {
    implementation("com.google.accompanist:accompanist-drawablepainter:<version>") // TODO: Replace <version> with actual version
}

示例:

Image(
    painter = rememberDrawablePainter(drawable = yourDrawable),
    contentDescription = yourContentDescriptionIfAny,
)

0
投票

我发现如果不添加就会出现错误: 内容描述 = null

背后的原因是什么?而且,我怎么知道我应该从错误消息中添加“内容描述”?我看不到任何与之相关的内容。


-1
投票

Google 更新了他们的 API。对于

0.1.0-dev03
加载图像是同步的并且是这样完成的

val icon = +imageResource(R.drawable.ic_xxx)

绘制图像

Container(modifier = Height(100.dp) wraps Expanded) {
   DrawImage(icon)
}

目前,上述代码依赖于您指定确切的高度或宽度。如果您想要例如 100 dp 高度和

wrap_content
而不是
Expanded
来扩展整个宽度,似乎不支持缩放图像。 有谁知道如何解决这个问题?也可以像旧方法一样将图像放入容器中
scaleType=fitCenter

© www.soinside.com 2019 - 2024. All rights reserved.