https://kotlinlang.org logo
Title
d

dbaelz

07/23/2021, 9:36 AM
I've posted a Compose puzzler on Twitter about multiple
Modifier.border()
that overdraw each other (link and code in the thread). Gave an explanation why it's this way, but after I read it again I'm unsure if it's correct and I have second thoughts. Can someone shed some light into the topic?
The tweet with the code and in the thread the explanation: https://twitter.com/dbaelz/status/1418134001232056320 The code
@ExperimentalFoundationApi
@Composable
private fun ModifierBorderPuzzler(borderWidth: Dp = 12.dp) {
    Box(
        modifier = Modifier
            .size(200.dp)
            .border(borderWidth, Color.Gray)
            .border(borderWidth, Color.Cyan)

            .padding(borderWidth)

            .border(borderWidth, Color.Blue)
            .border(borderWidth, Color.Magenta)

            .padding(borderWidth)

            .border(borderWidth, Color.Yellow)
            .border(borderWidth, Color.Black)

            .padding(borderWidth)
    )
}
Results into a border (outer to inner): Gray > Blue > Yellow
a

Albert Chang

07/23/2021, 10:03 AM
Actually the drawing order of modifiers can be controlled by putting the drawing code before of after the
drawContent()
call in `ContentDrawScope`:
Modifier.drawWithCache { 
    onDrawWithContent { 
        // Draw behind
        drawContent()
        // Draw above
    }
}
In the case of
Modifier.border()
, the drawing code (e.g. here) is after
drawContent()
so earlier borders are above later borders (the border drawn by the second modifier becomes the first modifier's content and so on).
👍 1
d

dbaelz

07/23/2021, 10:37 AM
Thanks. Yeah, I looked into the
Border
class and saw the
drawContent()
method, but didn't get it that detailed from the documentation. Cool that you pointed that out! Is it common for (framework) Composables to have this drawing order? It surely has it advantages, but might not be very intuitiv when it comes to modifier order (for this very special case).
a

Albert Chang

07/23/2021, 10:44 AM
It depends. I guess in this case it's just because it makes more sense that the border is drawn above the content as the border is drawn within the content's bounds.