To move a shape around, I can use Modifier.pointer...
# compose
n
To move a shape around, I can use Modifier.pointerInput etc. Now how about a rectangle on canvas? As there is no Modifier. Is there a way with Compose or should I use the native way?
k
many methods in
PointerInputChange
return an
Offset
, perhaps you can use those?
n
Thanks, this looks interesting! Implementing it does not look obvious though, but I'll give it a shot.
z
If you’re drawing a rectangle on a canvas, you have to explicitly pass the bounds. You move it by passing different bounds. If you’re trying to control the position from somewhere else like a gesture filter, store the bounds in a MutableState and share that state between your canvas and your gesture filter.
n
Thanks @Zach Klippenstein (he/him) [MOD], but what shall I use as "gesture filter"?
z
That’s the pointer input change thing
n
ah ok cheers! 🙂
n
Copy code
var offsetX by remember { mutableStateOf(0f) }
var offsetY by remember { mutableStateOf(0f) }

Canvas(modifier = Modifier.fillMaxSize()
        .pointerInput(Unit) {
            detectDragGestures { change, dragAmount ->
                change.consumeAllChanges()
                offsetX += dragAmount.x
                offsetY += dragAmount.y
            }
        }
    ){
    val canvasQuadrantSize = size / 2F
    drawRect(
        topLeft = Offset(offsetX,offsetY),
        color = Color.Green,
        size = canvasQuadrantSize
    )
}
k
A bit unclear on "move around several rectangles individually". Do you mean that you can have 10 rectangles on the canvas, and be able to grab-and-drag each one separately? Or select a few rectangles and drag them as a group? In any case, you would need to track what is selected (one or more), and individual offsets for separate rectangles.
n
Yes, I mean having 10 rectangles on the canvas, and be able to grab-and-drag each one separately.
Thanks, I'll try I work it out. 🙂
k
At some point when you'd want to move this out of an exploratory phase, you'd have each rectangle represented by some sort of a model object that is persisted somewhere as part of your data model / document. Each such object would have offset, size, maybe color, maybe opacity, maybe rotation angle, etc. So those fields would be used to draw each object on the canvas. User interaction with the canvas would be broken into selection gestures (click to select one object, click to deselect, click in an empty area to start multi-select, ctrl+click to multi-select, etc) and modification gestures (resize, rotate, etc).
🙏 1
n
Makes sense, cheers again!