如何使用 Modifier.graphicsLayer{}.pointerInput() 实现自然的平移和缩放?

Thr*_*ian 7 android android-jetpack-compose android-jetpack-compose-gesture

Modifier.graphicsLayer{}这与使用旋转或平移图像不同。我想要在屏幕上移动、旋转和缩放可组合项,而不是在固定位置。

我想要实现的目标如下图所示

在此输入图像描述

Modifier.graphicsLayer{}和的顺序Modifier.pointerInput()很重要。如果Modifier.pointerInput()放置在Modifier.graphicsLayer{}Composable 的触摸区域缩放、平移和旋转之后。

@Composable
private fun Test() {

    var offsetLeft by remember { mutableStateOf(Offset.Zero) }
    var offsetRight by remember { mutableStateOf(Offset.Zero) }

    var rotationLeft by remember { mutableStateOf(0f) }
    var rotationRight by remember { mutableStateOf(0f) }

    val modifierLeft = Modifier
        .border(3.dp, Color.Red)
        .graphicsLayer {
            translationX = offsetLeft.x
            translationY = offsetLeft.y
            rotationZ = rotationLeft
        }
        .border(2.dp, Color.Green)
        .pointerInput(Unit) {
            detectTransformGestures { centroid, pan, zoom, rotation ->
                offsetLeft += pan
                rotationLeft += rotation
            }
        }


    val modifierRight = Modifier
        .border(3.dp, Color.Red)
        .pointerInput(Unit) {
            detectTransformGestures { centroid, pan, zoom, rotation ->
                offsetRight += pan
                rotationRight += rotation
            }
        }
        .border(2.dp, Color.Green)
        .graphicsLayer {
            translationX = offsetRight.x
            translationY = offsetRight.y
            rotationZ = rotationRight
        }


    Row(modifier = Modifier.fillMaxSize()) {
        Image(
            painter = painterResource(id = R.drawable.landscape1),
            contentDescription = "",
            modifierLeft.aspectRatio(1f).weight(1f)
        )
        Image(
            painter = painterResource(id = R.drawable.landscape1),
            contentDescription = "",
            modifierRight.aspectRatio(1f).weight(1f)
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够移动、旋转和像 gif 中的左图像一样从其当前转换中实现可组合。

在此输入图像描述

到目前为止我所做的,我通过旋转矩阵旋转平移

/**
 * Rotates the given offset around the origin by the given angle in degrees.
 *
 * A positive angle indicates a counterclockwise rotation around the right-handed 2D Cartesian
 * coordinate system.
 *
 * See: [Rotation matrix](https://en.wikipedia.org/wiki/Rotation_matrix)
 */
fun Offset.rotateBy(
    angle: Float
): Offset {
    val angleInRadians = ROTATION_CONST * angle
    val newX = x * cos(angleInRadians) - y * sin(angleInRadians)
    val newY = x * sin(angleInRadians) + y * cos(angleInRadians)
    return Offset(newX, newY)
}

internal const val ROTATION_CONST = (Math.PI / 180f).toFloat()
Run Code Online (Sandbox Code Playgroud)

它适用于平移,平移工作正常,但随着从原始位置的平移增加旋转和缩放似乎不起作用。我无法正确翻译位置。

@Composable
private fun MyComposable() {

    var offset by remember { mutableStateOf(Offset.Zero) }
    var zoom by remember { mutableStateOf(1f) }
    var rotation by remember { mutableStateOf(0f) }
    var text by remember { mutableStateOf("") }
    var centroid by remember { mutableStateOf(Offset.Zero) }


    val modifier = Modifier
        .border(3.dp, Color.Green)
        .fillMaxWidth()
        .aspectRatio(4 / 3f)
        .graphicsLayer {
            this.translationX = offset.x * zoom
            this.translationY = offset.y * zoom
            this.scaleX = zoom
            this.scaleY = zoom
            this.rotationZ = rotation
//            TransformOrigin(0f, 0f)
        }
        .pointerInput(Unit) {
            detectTransformGestures(
                onGesture = { gestureCentroid, gesturePan, gestureZoom, gestureRotate ->

                    rotation += gestureRotate
                    zoom *= gestureZoom
                    offset += gesturePan.rotateBy(rotation)
                    centroid = gestureCentroid

                }
            )
        }
        .drawWithContent {
            drawContent()
            drawCircle(color = Color.Red, center = centroid, radius = 20f)
        }

    Image(
        modifier = modifier,
        painter = painterResource(id = R.drawable.landscape1),
        contentDescription = null,
        contentScale = ContentScale.FillBounds
    )
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我尝试更改 TransformOrigin()。还更新了适用于固定触摸位置的示例代码,这是developer.android 页面中可用代码的修改版本

@Composable
private fun MyComposable3() {

    var zoom by remember { mutableStateOf(1f) }
    var offset by remember { mutableStateOf(Offset.Zero) }
    var centroid by remember { mutableStateOf(Offset.Zero) }
    var centroidOld by remember { mutableStateOf(Offset.Zero) }
    var centroidNew by remember { mutableStateOf(Offset.Zero) }
    var angle by remember { mutableStateOf(0f) }


    val imageModifier = Modifier

        .border(3.dp, Color.Green)
        .graphicsLayer {
            translationX = -offset.x * zoom
            translationY = -offset.y * zoom
            scaleX = zoom
            scaleY = zoom
            rotationZ = angle
            TransformOrigin(0f, 0f).also { transformOrigin = it }
        }
        .pointerInput(Unit) {
            detectTransformGestures(
                onGesture = { gestureCentroid, gesturePan, gestureZoom, gestureRotate ->
                    val oldScale = zoom
                    val newScale = (zoom * gestureZoom).coerceIn(0.5f..5f)

                    angle += gestureRotate

                    // For natural zooming and rotating, the centroid of the gesture should
                    // be the fixed point where zooming and rotating occurs.

                    // We compute where the centroid was (in the pre-transformed coordinate
                    // space),
                    // and then compute where it will be after this delta.

                    // We then compute what the new offset should be to keep the centroid
                    // visually stationary for rotating and zooming, and also apply the pan.

                    centroidOld = (offset + gestureCentroid / oldScale).rotateBy(gestureRotate)
                    centroidNew =
                        (gestureCentroid / newScale + gesturePan.rotateBy(angle) / oldScale)

                    offset = centroidOld - centroidNew

                    zoom = newScale

                    centroid = gestureCentroid
                }
            )
        }


        .border(3.dp, Color.Red)
        .drawWithContent {
            drawContent()
            drawCircle(color = Color.Red, center = centroid, radius = 20f)
            drawCircle(color = Color.Green, center = centroidOld, radius = 20f)
            drawCircle(color = Color.Blue, center = centroidNew, radius = 20f)
        }

    Image(
        modifier = imageModifier
            .fillMaxWidth()
            .aspectRatio(4 / 3f),
        painter = painterResource(id = R.drawable.landscape2),
        contentDescription = null,
        contentScale = ContentScale.FillBounds
    )
}
Run Code Online (Sandbox Code Playgroud)

这个也不起作用。

小智 1

您将无法使用graphicLayer修饰符成功修改可组合放置,文档说:

Modifier.graphicsLayer 不会更改可组合项的测量大小或位置,因为它仅影响绘制阶段。这意味着如果您的可组合项最终在其布局边界之外绘制,则它可能会与其他可组合项重叠。

尝试改用布局修饰符:

var scale by remember { mutableStateOf(1f) }
var rotation by remember { mutableStateOf(0f) }
var offset by remember { mutableStateOf(Offset.Zero) }
val transformationState = rememberTransformableState { zoomChange, offsetChange, rotationChange ->
    scale *= zoomChange
    rotation += rotationChange
    offset += offsetChange
}
val modifier = Modifier
    .rotate(rotation)
    .scale(scale)
    .layout { measurable, constraints ->
        val placeable = measurable.measure(constraints)
        layout(
            placeable.width,
            placeable.height
        ) {
            this.coordinates
            placeable.placeRelative(offset.toIntOffset())
        }
    }
    .transformable(state = transformationState)
    .border(2.dp, Color.Green)
Run Code Online (Sandbox Code Playgroud)

您可以在这里找到更多信息。