https://kotlinlang.org logo
#compose
Title
# compose
a

Albert Chang

03/04/2021, 9:57 AM
Is there any way to draw onto an independent layer with transparent background?
graphicsLayer()
doesn't seem to work. (Details in thread)
Copy code
Canvas(Modifier.fillMaxWidth().height(200.dp).graphicsLayer()) {
    drawRect(
        Color.Blue,
        topLeft = Offset(size.width / 3, 0f),
        size = Size(size.width / 3, size.height)
    )
    drawRect(
        Color.Red,
        topLeft = Offset(0f, size.height / 3),
        size = Size(size.width, size.height / 3),
        blendMode = BlendMode.Xor
    )
}
This results in the first, while what I want is the second.
n

Nader Jawad

03/04/2021, 8:07 PM
I believe we might need to force a composition layer to support some blendmode operations. We force this implicitly whenever alpha is applied to a graphicsLayer but we don't expose a way to force it directly. As a test if you try providing a slight opacity like 0.99f on the graphics layer it might get the result you are looking for.
Yup just tried the following and I got what looks like the intended output:
Copy code
// Configure alpha to almost 1 but not quite 1 to force graphics layer into
    // offscreen composition to ensure XOR blends against transparent pixels
    // otherwise the contents are drawn directly
    Canvas(Modifier.fillMaxWidth().height(200.dp).graphicsLayer(alpha = 0.99f)) {
        drawRect(
            Color.Blue,
            topLeft = Offset(size.width / 3, 0f),
            size = Size(size.width / 3, size.height)
        )
        drawRect(
            Color.Red,
            topLeft = Offset(0f, size.height / 3),
            size = Size(size.width, size.height / 3),
            blendMode = BlendMode.Xor
        )
    }
🙏 1
In the future it will look something like
useCompositingLayer = true
instead of using alpha to force this behavior
👍 2
3 Views