如何在 Jetpack Compose 中将颜色资源转换为 Color 对象?

Ioa*_* P. 4 android kotlin android-jetpack-compose

我有一个文本,我想画一个圆圈,该圆圈的颜色应该存在于我的资源文件中。

Text(
    modifier = Modifier.align(Alignment.TopEnd).drawBehind {
        drawCircle(
            color = colorResource(R.color.primary),
            radius = 96.00f
        )
    },
    text = "X"
)
Run Code Online (Sandbox Code Playgroud)

但我得到:

@Composable 调用只能在 @Composable 函数的上下文中发生

如果我使用color = Color.Red,效果很好。所以我不想使用任何这些颜色,我想使用我的颜色。所以我想进行转换,但我找不到任何解决方案。我怎样才能转换它?

Thr*_*ian 6

You need to call Composable functions from a scope that has @Composable annotation.

Box() {
  val color = colorResource(R.color.black)
  Text(
      modifier = Modifier.align(Alignment.TopEnd).drawBehind {
          drawCircle(
              color = color,
              radius = 96.00f
          )
      },
      text = "X"
  )
}
Run Code Online (Sandbox Code Playgroud)

colorResource is a @Composable function

@Composable
@ReadOnlyComposable
fun colorResource(@ColorRes id: Int): Color {
    val context = LocalContext.current
    return if (Build.VERSION.SDK_INT >= 23) {
        ColorResourceHelper.getColor(context, id)
    } else {
        @Suppress("DEPRECATION")
        Color(context.resources.getColor(id))
    }
}
Run Code Online (Sandbox Code Playgroud)

but lambda of Modifier.drawBehind isn't

fun Modifier.drawBehind(
    onDraw: DrawScope.() -> Unit
) = this.then(
    DrawBackgroundModifier(
        onDraw = onDraw,
        inspectorInfo = debugInspectorInfo {
            name = "drawBehind"
            properties["onDraw"] = onDraw
        }
    )
)
Run Code Online (Sandbox Code Playgroud)

You can check this answer for difference between function, lambdas or params with @Composable annotation or the ones without