https://kotlinlang.org logo
Title
g

Guilherme Delgado

05/02/2022, 9:01 PM
Is there any
android.graphics.Camera
equivalent (for 3D operations) so we can perform code like this:
val matrix = android.graphics.Matrix() //we have androidx.compose.ui.graphics.Matrix
val camera = Camera()
    
drawScope.drawIntoCanvas { canvas ->
        //camera transformations like camera.rotateZ, etc..
        camera.getMatrix(matrix)
        matrix.preTranslate(-x, -y)
        matrix.postTranslate(x, y)

        canvas.save()
        canvas.nativeCanvas.concat(matrix)
        drawScope.draw...
        canvas.restore()
}
Thanks.
m

Michael Paus

05/03/2022, 9:34 AM
Can’t you directly use the transform operations provided by the draw scope or the canvas? Why do you need a camera for that?
g

Guilherme Delgado

05/03/2022, 9:57 AM
Because in Android we use the Camera for 3D (x,y,z) operations, with drawScope/Canvas I only have 2D (x,y)
m

Michael Paus

05/03/2022, 10:43 AM
But in your example code above you are not using any 3D transforms. According to my understanding the Camera class is just a helper class to extract the 2D part from a 3D transform. I haven’t tried it but I assume that the Camera class source code could be easily adapted to Compose.
g

Guilherme Delgado

05/03/2022, 10:44 AM
I didn’t put a complete example only:
//camera transformations like camera.rotateZ, etc..
On Android that’s how I’ve created this, but I’m struggling to find similar in Compose Desktop.
m

Michael Paus

05/03/2022, 10:58 AM
As I said, the Camera class does not seem to be readily available in Compose desktop but you might want to have a look at the original Android code. Edit: The Android Camera class seems to be backed by some native code and thus cannot be adapted.
On a closer look I think much of what you can do with the Camera in Android can already be done with the Compose Matrix class directly. https://developer.android.com/reference/kotlin/androidx/compose/ui/graphics/Matrix
1
g

Guilherme Delgado

05/03/2022, 11:20 AM
Thanks, gonna have a look 👍
example:
val matrix = Matrix()
matrix.rotateX(45f)
matrix.rotateY(45f)
matrix.rotateZ(45f)
drawContext.canvas.save()
drawContext.canvas.concat(matrix)

draw...

drawContext.canvas.restore()
Seems to work 🙂
m

Michael Paus

05/03/2022, 11:40 AM
Nice, and that code will work on Android AND Desktop,.
:kotlin-intensifies: 1
This code could be further improved by using something like this:
drawScope.withTransform({transform(matrix)}) {
    ...
}
This should avoid all these concat/save/restore
👌 1