はじめに
JetpackComposeでドラッグ中のViewを拡大する
前回の↑こちらに記事に、「押している間は色を変える」という処理を追加しました。
よければそちらもご覧ください。
それ以外にも軽く修正を含みます。
実践
@Composable
fun ScalableButton(
modifier: Modifier = Modifier,
onClick: () -> Unit,
content: @Composable () -> Unit
) {
// 押下状態
var pressed by remember { mutableStateOf(false) }
// 拡大アニメーション
val scale by animateFloatAsState(
targetValue = if (pressed) 1.1f else 1f,
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
),
label = "scale"
)
// 色アニメーション
val backgroundColor by animateColorAsState(
targetValue = if (pressed) Color(0xFF1565C0) else Color(0xFF2196F3),
animationSpec = tween(durationMillis = 150),
label = "backgroundColor"
)
Box(
modifier = modifier
.graphicsLayer(
scaleX = scale,
scaleY = scale
)
.background(backgroundColor, shape = CircleShape)
// ↓ Compose標準の押下検知+クリックを統合
.combinedClickable(
onClick = { onClick() },
onLongClick = {}, // 長押し不要なら空でOK
onClickLabel = null,
onLongClickLabel = null,
interactionSource = remember { MutableInteractionSource() },
indication = null // Rippleを消したい場合
)
// ↓ 押している間を監視
.pointerInput(Unit) {
awaitEachGesture {
val down = awaitFirstDown()
pressed = true
try {
// 指を離す or キャンセルされるまで待つ
waitForUpOrCancellation()
} finally {
pressed = false
}
}
},
contentAlignment = Alignment.Center
) {
content()
}
}
Box(
modifier = Modifier
contentAlignment = Alignment.Center // 中央に配置
) {
ScalableButton(
onClick = { println("Clicked!") },
modifier = Modifier.size(120.dp)
) {
Text(
text = "押して!",
color = Color.White,
fontSize = 18.sp
)
}
}