0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jetpack ComposeでドラッグしたViewを回転させる方法

0
Posted at

はじめに

前回に引き続き、もともとViewでやっていたアニメーションの動きの記事をJetpackCompose
でも実現させていきます。

前回の記事はこちら

元にした記事はこちら

実践

@Composable
fun DraggableRotateBox() {

    var offsetX by remember { mutableStateOf(0f) }
    var offsetY by remember { mutableStateOf(0f) }

    // 回転角度
    var rotation by remember { mutableStateOf(0f) }

    Box(
        modifier = Modifier
            .size(100.dp)
            .offset {
                IntOffset(offsetX.roundToInt(), offsetY.roundToInt())
            }
            .graphicsLayer {
                rotationZ = rotation // ← 回転
            }
            .background(Color.Red)
            .pointerInput(Unit) {
                detectDragGestures { change, dragAmount ->
                    change.consume()

                    // 位置移動
                    offsetX += dragAmount.x
                    offsetY += dragAmount.y

                    rotation += dragAmount.x * 0.5f
                }
            }
    )
}

解説

rotation += dragAmount.x * 0.5f

dragAmount.xを使うことで、

  • 右に動かす → 時計回り
  • 左に動かす → 反時計回り
    を実現させる。

回転量を調整したい場合はここの数字を調整する。

実際に回転させている箇所は以下で、
Composeでは view.rotation の代わりにこれを使う

.graphicsLayer {
    rotationZ = rotation
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?