`AppWindowAmbient.current.y` gives the top locatio...
# compose-desktop
k
AppWindowAmbient.current.y
gives the top location of the current desktop window. Is there a way to get the vertical offset from the window top for
Canvas
or
DrawScope
? That would allow doing vertical gradients across multiple composables without trying to place them into a common container.
t
ther is a modifier:
Copy code
onGloballyPositioned
but i am not sure if it is a good idea to use the position during animation. But for static drawing it should be fine.
k
Is that for a whole window, or available for every canvas? I'm very much interested in a more focused solution to positioning content based on location in window. This is available in pretty much every toolkit.
t
you get the bounding box of the component inside the window. So i think that is what you want.
Every component in compose can define modifiers. So you can not only use this to draw inside of a canvas. You can also use this to define padding or s.th. else
k
Ah, excellent, this gives me the info I needed. I do
Copy code
val offset = remember { mutableStateOf(Offset(0.0f, 0.0f)) }
And then on the
Box
that has my `Canvas`:
Copy code
.onGloballyPositioned {
    offset.value = it.localToRoot(Offset(0.0f, 0.0f))
}
And then
offset.value.y
gives me the offset of "this" box relative to the window root. Thanks, Timo!
I'm sure I'll get yelled at for this abomination:
Copy code
private class MyBackground(private val color: Color) : OnGloballyPositionedModifier, DrawModifier {
    var offset = Offset(0.0f, 0.0f)

    override fun onGloballyPositioned(coordinates: LayoutCoordinates) {
        offset = coordinates.localToRoot(Offset(0.0f, 0.0f))
    }

    override fun ContentDrawScope.draw() {
        println(offset.y)
        drawRect(color = color)
        drawContent()
    }
}
But the end result is that I get the right offset in
.draw()
and it gets recomposed when I resize the window and the relevant containers that use such a composite modifier get resized.
t
👍 maybe someone else know a better solution?
Not sure about this coordinates.localToRoot. It should be already global.
But when it works 😄
k
Global is the desktop coordinates, right? If so, I need to convert those to the offset from the window root. I tried a couple of things with global conversions and at some point I was getting into an infinite recomposition loop.