如何获取Compose Canvas当前应用的平移、旋转与缩放参数?
如何在Compose的DrawScope中获取当前画布的平移、旋转和缩放参数
可以通过DrawScope获取当前画布的变换参数——DrawScope内部维护了所有嵌套withTransform叠加后的累积变换矩阵,只需从这个矩阵中解析出对应的平移、旋转和缩放信息即可。
具体实现步骤
- 获取当前变换矩阵:直接调用DrawScope的
transformMatrix属性,拿到最终的累积变换矩阵。 - 从矩阵中解析参数:通过矩阵的数值数组,提取出缩放、旋转、平移的具体数值。
代码示例
结合你的原有代码,实现如下:
import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Matrix import androidx.compose.ui.graphics.drawscope.withTransform import androidx.compose.ui.unit.dp @Composable fun TransformInfoCanvas() { Canvas(modifier = Modifier.fillMaxSize()) { // 示例变换矩阵1:缩放+平移 val matrix1 = Matrix().apply { scale(1.5f, 1.5f) translate(50f, 50f) } // 示例变换矩阵2:旋转 val matrix2 = Matrix().apply { rotate(30f) } withTransform( { transform(matrix = matrix1) } ) { withTransform( { transform(matrix = matrix2) } ) { // 获取当前累积变换矩阵 val currentMatrix = transformMatrix val matrixValues = FloatArray(9) currentMatrix.getValues(matrixValues) // 提取缩放参数:x轴缩放为values[0],y轴为values[4] val scaleX = matrixValues[0] val scaleY = matrixValues[4] // 提取旋转角度:通过反正切计算弧度,再转为角度 val rotationRadians = kotlin.math.atan2(matrixValues[1], matrixValues[0]) val rotationDegrees = Math.toDegrees(rotationRadians.toDouble()).toFloat() // 提取平移参数:x平移为values[2],y平移为values[5] val translationX = matrixValues[2] val translationY = matrixValues[5] // 绘制参数信息 drawText( text = "缩放: (${scaleX.format(2)}, ${scaleY.format(2)}) \n旋转: ${rotationDegrees.format(1)}° \n平移: (${translationX.format(0)}, ${translationY.format(0)})", color = Color.Black, topLeft = Offset(16.dp.toPx(), 16.dp.toPx()) ) } } } } // 扩展函数:格式化浮点数显示 fun Float.format(digits: Int): String = "%.${digits}f".format(this)
关键说明
- Compose的
Matrix是3x3的行优先矩阵,数值数组的索引对应关系如下:[0] [1] [2] → 缩放X/旋转分量 | 旋转分量/切变Y | 平移X [3] [4] [5] → 旋转分量/切变X | 缩放Y/旋转分量 | 平移Y [6] [7] [8] → 透视相关(2D变换中通常为0, 0, 1) - 上述解析方式适用于仅包含平移、旋转、缩放的变换场景。如果变换中包含切变(skew),旋转角度的计算会受切变影响,需要更复杂的矩阵分解逻辑。
内容的提问来源于stack exchange,提问作者Augusto Carmo
相关产品推荐
相关产品推荐

