実践
@Composable
fun ClickToShakeView() {
val shakeOffset = remember { Animatable(0f) }
val coroutineScope = rememberCoroutineScope()
fun triggerShake() {
coroutineScope.launch {
val vibrationPattern = listOf(-10f, 10f, -8f, 8f, -6f, 6f, -4f, 4f, 0f)
vibrationPattern.forEach {
shakeOffset.animateTo(
targetValue = it,
animationSpec = tween(durationMillis = 30)
)
}
}
}
Box(
modifier = Modifier
.offset(x = shakeOffset.value.dp)
.size(100.dp)
.background(Color.Red)
.clickable {
triggerShake()
},
contentAlignment = Alignment.Center
) {
Text("クリック", color = Color.White)
}
}
説明
Animatable を使って、Viewの横方向の位置をアニメーションで動かしています。
vibrationPattern は震える動きのパターンをListにしている。ここを数字をいじれば震え方をアレンジできる。
Modifier.offset でX方向にビューを動かす。