2
votes

I have a canvas with a rectangle that I would like to be able to move around. With a Composable, I know how to use the dragging modifier as described here: https://developer.android.com/jetpack/compose/gestures#dragging

But my canvas rectangle has no modifier:

Canvas(modifier = Modifier.fillMaxSize()) {
        drawRect(Color.Blue, topLeft = Offset(0f, 0f), size = Size(this.size.width, 55f))

So how can I drag it? Is there a way with Compose or is it better to just use the native way with a native canvas?

1

1 Answers

5
votes

With 1.0.0-beta04 you can use the pointerInput modifier in the Canvas to control the dragging gesture through the detectDragGestures function and save the Offset and apply it in the topLeft parameter in the drawRect.

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
    )
}

enter image description here