我使用 Android Studios 资源管理器导入了一些图像作为可绘制对象。
它将在 Jetpack Compose Android 应用程序中用作背景图像。它在夜间和白天模式下按预期工作。
但是应用程序中有一个部分,用户可以从这些背景列表中进行选择。该列表应显示白天和夜间模式下每个背景的预览。
像这样:
当我显示图像时,我是这样做的:
Image(painter = painterResource(id = R.drawable.my_image))
所以我总是获取当前所选模式的图像。但我想明确请求图像的深色和浅色变体并排显示它们。
我想象了这样的事情:
Image(painter = painterResource(id = R.drawable.my_image, isDark = false))
Image(painter = painterResource(id = R.drawable.my_image, isDark = true))
我知道这个API不存在。但是我怎样才能检索不适合当前上下文的图像呢?
正如here所解释的,Jetpack compose 确定主题如下。
val isDarkTheme = isSystemInDarkTheme()
在您的情况下,您需要提供位于默认可绘制资源文件夹中的两个可绘制资源。
然后,创建一个可组合函数,如下所示。
@Composable
fun SelectableImageView() {
val isDarkTheme = isSystemInDarkTheme()
val imageRes = if (isDarkTheme) R.drawable.image_dark else R.drawable.image_light
Image(painter = painterResource(id = imageRes)
}