I have a Text and I want to draw a circle that should have a color that exists inside my resource file.
Text(
modifier = Modifier.align(Alignment.TopEnd).drawBehind {
drawCircle(
color = colorResource(R.color.primary),
radius = 96.00f
)
},
text = "X"
)
But I get:
@Composable invocations can only happen from the context of a @Composable function
If I use color = Color.Red
, it works fine. So I don't want to use any of those colors, I want to use mine. So I thought to make a conversion, but I cannot find any solution. How can I convert that?
CodePudding user response:
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"
)
}
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))
}
}
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
}
)
)
You can check this answer for difference between function, lambdas or params with @Composable annotation or the ones without