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?

JetpackCompose スワイプ中の指に追従する画像の実装方法

Posted at

スワイプ中の指に追従する画像の実装方法です。

このような感じの実装です。
Videotogif (1).gif

SampleImage.kt
@Composable
fun SampleImage() {
    var position by remember { mutableStateOf(Offset.Zero) }
    val imageSize = 64.dp
    val density = LocalDensity.current

    BoxWithConstraints(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
            .pointerInput(Unit) {
                detectDragGestures { change, _ ->
                    position = change.position
                }
            }
    ) {
        val boxWidth = constraints.maxWidth.toFloat()
        val boxHeight = constraints.maxHeight.toFloat()

        LaunchedEffect(Unit) {
            position = Offset(boxWidth / 2, boxHeight / 2)
        }

        val imageOffset = with(density) { (imageSize / 2).toPx() }

        Image(
            painter = painterResource(id = R.drawable.baseline_back_hand),
            contentDescription = "追従する画像",
            modifier = Modifier
                .offset {
                    IntOffset(
                        (position.x - imageOffset).toInt(),
                        (position.y - imageOffset).toInt()
                    )
                }
                .size(imageSize)
        )
    }
}

pointerInputを使用してジェスチャーを取得し、スワイプしているポジションを取得します。
var position by remember { mutableStateOf(Offset.Zero) } こちらが表示位置です。
ImageModifier.offsetposition から画像サイズの半分を引いた数値を設定することで表現してます。

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?