Has anyone experienced a `java.lang.NullPointerExc...
# compose
j
Has anyone experienced a
java.lang.NullPointerException: null cannot be cast to non-null type androidx.compose.ui.graphics.AndroidPathEffect
when using a
androidx.compose.ui.graphics.PathEffect
on a
ContentDrawScope.drawCircle
?
I have defined the following component:
Copy code
val pathEffectIntervalsDp: Array<Dp> = arrayOf(6.dp, 3.dp)
val strokeWidthDp = 1.dp

@Suppress("UNUSED_VARIABLE")
@Composable
fun DashedCircle(
    strokeColor: Color,
    modifier: Modifier = Modifier,
) {
    val pathEffectIntervals: FloatArray = pathEffectIntervalsDp.map {
        with (AmbientDensity.current) { it.toPx() }
    }.toFloatArray()
    val strokeWidth = with (AmbientDensity.current) { strokeWidthDp.toPx() }
    Box(modifier.drawWithCache {
        val pathEffect: PathEffect = PathEffect.dashPathEffect(pathEffectIntervals, 1f)
        val start = Offset(size.width / 2, size.height / 2)
        val end = Offset(size.width, size.height / 2)

        onDrawWithContent {
            drawCircle(
                strokeColor,
                style = Stroke(
                    width = strokeWidth,
//                    pathEffect = pathEffect
                )
            )
            drawLine(
                color = strokeColor,
                start = start,
                end = end
            )
        }
    })
}
Which correctly renders this:
But If I uncomment the pathEffect line of the
drawCircle
, The error occurs on the preview and when running it. Strangely, if I remove the
drawLine
and only leave the
drawCircle
, it outputs correctly this:
I think this problem started happening in alpha09 when the
Stroke
stopped taking an
android.graphics.PathEffect
as
DashPathEffect(pathEffectIntervals, 1f)
to now take an a`ndroidx.compose.ui.graphics.PathEffect` as
PathEffect.dashPathEffect(pathEffectIntervals, 1f)
n
Thanks for raising this issue. I just root caused and pushed up a fix. DrawScope internally manages a Paint object and there is an issue where if the PathEffect parameter is non-null in one call then null in a subsequent draw call you run into null pointer exceptions as you have noted. For this specific example as a workaround you could try re-arranging the drawing order to draw the line first then the circle. Otherwise you can use the drawIntoCanvas API to manually draw into the canvas directly.
j
Amazing! Thank you, I will try that in the meantime 💯
Also if anyone might need it, here is the issue: https://issuetracker.google.com/issues/179062252
👍 1