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

はじめに

前回のこちらの記事の続きで、JetpackComposeでViewをドラッグして動かす処理を書きましたが、今度はその動かしたViewを放した時に「元の位置に戻す」と言うことをやっていきます。

@Composable
fun DraggableReturnBox() {

    // 現在位置
    var offsetX by remember { mutableStateOf(0f) }
    var offsetY by remember { mutableStateOf(0f) }

    // 元の位置
    val homeX = 0f
    val homeY = 0f

    // アニメーション付きで戻す
    val animatedOffsetX by animateFloatAsState(
        targetValue = offsetX,
        label = "offsetX"
    )
    val animatedOffsetY by animateFloatAsState(
        targetValue = offsetY,
        label = "offsetY"
    )

    Box(
        modifier = Modifier
            .size(100.dp)
            .offset {
                IntOffset(
                    animatedOffsetX.roundToInt(),
                    animatedOffsetY.roundToInt()
                )
            }
            .background(Color.Blue)
            .pointerInput(Unit) {
                detectDragGestures(
                    onDrag = { change, dragAmount ->
                        change.consume()

                        offsetX += dragAmount.x
                        offsetY += dragAmount.y
                    },
                    onDragEnd = {
                        // 元に戻す」処理
                        offsetX = homeX
                        offsetY = homeY
                    }
                )
            }
    )
}

リアルタイムの位置(offsetX,offsetY)と元の位置(homeX,homeY)を利用して、戻す動きを実現する。
戻すときに不自然にならないように、戻す際にもアニメーションで戻す。

untitled (1).gif

戻す処理を加えてもやはりJetpackComposeの方が簡潔に書けていい感じですね。

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?