スワイプ中の指に追従する画像の実装方法です。
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) }
こちらが表示位置です。
Image
のModifier.offset
にposition
から画像サイズの半分を引いた数値を設定することで表現してます。