How to rotate a canvas at a specific point using android.graphics.Camera.rotateX(angle)

前端 未结 4 1170
一向
一向 2021-02-06 12:27

I am trying to use the Camera (android.graphics.Camera not the hardware camera) to rotate a views canvas around a specific point, in this instance the middle of the canvas.

4条回答
  •  情话喂你
    2021-02-06 13:09

    Solved this, not sure if it's the best way but it works. The solution was to

    Translate the canvas first to center the larger canvas in the display

    Then apply the camera rotations

    Then to use the pre and post translate methods on the matrix to change the rotation point similar to what the android sample did.

    The missing bits were to do the canvas translation first, and I was also not using the larger canvas size to calculate the offsets for the pre and post translate methods.

    Here is the modified code if it helps anyone else out.

    // Center larger canvas in display (was made larger so
    // corners will not show when rotated) 
    canvas.translate(-translateX, -translateY); 
    
    // Use the camera to rotate a view on any axis
    camera.save();
        camera.rotateX(0);
        camera.rotateY(0);
        camera.rotateZ(angle); // Rotate around Z access (similar to canvas.rotate)                                 
    
        camera.getMatrix(cameraMatrix);
    
        // This moves the center of the view into the upper left corner (0,0) 
        // which is necessary because Matrix always uses 0,0, as it's transform point 
        cameraMatrix.preTranslate(-centerScaled, -centerScaled);
    
        // NOTE: Camera Rotations logically happens here when the canvas has the 
        // matrix applied in the canvas.concat method 
    
        // This happens after the camera rotations are applied, moving the view 
        // back to where it belongs, allowing us to rotate around the center or 
        // any point we choose 
        cameraMatrix.postTranslate(centerScaled, centerScaled);
    camera.restore();
    
    canvas.concat(cameraMatrix);
    

    If anyone has a better way or sees a problem please leave a comment.

提交回复
热议问题