How to know the current Translation, Rotation and Scale that are currently applied to a Compose (or View) Canvas?

220 Views Asked by At

Suppose I have the following Canvas on my compose screen:

Canvas(modifier = Modifier.fillMaxSize()) {
    withTransform(
        {
            transform(matrix = SOME_TRANSFORMATION_MATRIX_HERE)
        }
    ) {
        withTransform(
            {
                transform(matrix = SOME_OTHER_TRANSFORMATION_MATRIX_HERE)
            }
        ) {
            // How to know the current canvas'
            //  - translation;
            //  - rotation, and;
            //  - scale?
        }
    }
}

Is it possible to know those transformations with the DrawScope? If so, how can one do it?

1

There are 1 best solutions below

3
On

To access the transformation matrix and its components in Jetpack Compose, you would typically need to implement your own transformation logic and maintain the state within your Composable function.

Here's a revised example of how you can maintain and access the transformation state in Compose:

@Composable
fun MyCanvas() {
    var translationX by remember { mutableStateOf(0f) }
    var translationY by remember { mutableStateOf(0f) }
    var rotationDegrees by remember { mutableStateOf(0f) }
    var scaleX by remember { mutableStateOf(1f) }
    var scaleY by remember { mutableStateOf(1f) }

    Canvas(modifier = Modifier.fillMaxSize()) {
        withTransform({
            // Apply transformations here
            translate(left = translationX, top = translationY)
            rotate(degrees = rotationDegrees)
            scale(scaleX, scaleY)
        }) {
            // Drawing code

            // Update transformation values as needed
            translationX = 100f
            translationY = 50f
            rotationDegrees = 45f
            scaleX = 1.5f
            scaleY = 1.5f

            // Now, you can access the current transformation values
            val currentTranslationX = translationX
            val currentTranslationY = translationY
            val currentRotationDegrees = rotationDegrees
            val currentScaleX = scaleX
            val currentScaleY = scaleY
        }
    }
}

In this approach, we're maintaining the transformation properties as mutable state variables, and when you want to update them, you can do so within the Composable function. This will allow you to both apply transformations to the Canvas and access their current values.

Jetpack Compose doesn't offer direct access to the transformation state of the Canvas or the DrawScope, so you need to handle the state yourself.