Foenix
Foenix

Reputation: 558

How to draw on canvas and apply color from palette provided by CompositionLocalProvider

Canvas(modifier = Modifier.size(91.dp), onDraw = {
                drawCircle(color = MaterialTheme.colorScheme.primary)
            })

Compiler gives an error : @Composable invocations can only happen from the context of a @Composable function and underline colorScheme. Also, I cannot apply my palette to AndroidView, like PieChart. I provided the color scheme through CompositionLocalProvider, like this

  CompositionLocalProvider(
    LocalColors provides colors,
    LocalTextStyles provides textStyles
) {...}

Example:

 AndroidView(factory = { context ->
    PieChart(context).apply {
        layoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT,
        )
        this.description.isEnabled = false

        this.isDrawHoleEnabled = false
        this.holeRadius = 60f
        this.transparentCircleRadius = 0f
        this.legend.isEnabled = false
        this.setHoleColor(LocalColors.current.OnBackground.toArgb()) //here is an error
    }
},

with the same result. My color scheme depends from dark or lite system colors. How should I fix this?

Upvotes: 1

Views: 799

Answers (2)

MrPlow
MrPlow

Reputation: 1234

You need to move the MaterialTheme.colors.primary (or colorScheme.primary) outside of the onDraw callback. The onDraw callback is not a composable context but the MaterialTheme.colorScheme propery is composable.

            val primaryColor = MaterialTheme.colors.primary
            Canvas(modifier = Modifier, onDraw = {
                drawCircle(primaryColor)
            })

In the second bit, you don't have a composable context there at all. It looks like in that case, you'd want to do something like this: https://stackoverflow.com/a/14468034/1091864

Upvotes: 2

Winston
Winston

Reputation: 48

OnBackground.toArgb()) //here is an error - I think you're calling an event 'OnBackground' and not the event result.

Upvotes: 0

Related Questions