Skip to content

Instantly share code, notes, and snippets.

@TuenTuenna
Last active September 3, 2021 07:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TuenTuenna/3bbd0c491ea722fa8f04426775393fa2 to your computer and use it in GitHub Desktop.
Save TuenTuenna/3bbd0c491ea722fa8f04426775393fa2 to your computer and use it in GitHub Desktop.
Android Compose Animation - Shake hands

안드 콤포즈 손흔드는 애니메이션

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ShakeHandViewTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    ShakeHandView()
                }
            }
        }
    }
}

// 손 흔드는 애니메이션 뷰
@Composable
fun ShakeHandView(){
    // 벡터 이미지 가져오기
    val sampleImg: Painter = painterResource(id = R.drawable.ic_hand)
    val infiniteTransition = rememberInfiniteTransition() // 무한 애니메이션
    val duration: Int = 600 // 애니메이션 지속시간
    val degree by infiniteTransition.animateFloat( // 앵글 애니메이션
        initialValue = -45f,
        targetValue = 45f,
        animationSpec = infiniteRepeatable(
            animation = tween(durationMillis = duration,
                easing = LinearEasing),
            repeatMode = RepeatMode.Reverse
        )
    )
    val startX: Float = .1f //
    val endX: Float = .1f // 조절을 위한 값

    // Box 는 층을 이루는 레이아웃입니다. withConstaints 를 하게 되면
    // 레이아웃의 요소에 offset 등의 컨스트레인트 값을 줄 수 있습니다.
    BoxWithConstraints(
        Modifier // 배경을 빨간색으로 꽉 채우기
            .fillMaxHeight()
            .fillMaxWidth()
            .background(Color(0xFFE02262))
    ){
        val start = -(maxWidth * startX)
        val end = (maxWidth * endX)
        val x by infiniteTransition.animateFloat( // x 축 애니메이션 값
            initialValue = start.value,
            targetValue = end.value,
            animationSpec = infiniteRepeatable(
                animation = tween(duration,
                    easing = LinearEasing),
                repeatMode = RepeatMode.Reverse
            )
        )
        Image( // 이미지 뷰
            painter = sampleImg,
            contentScale = ContentScale.Crop,
            contentDescription = "손 입니다",
            modifier = Modifier
                .offset(x = x.dp) // x 축 애니메이션이 여기서 적용
                .height(120.dp).width(120.dp) // 크기 지정
                .align(Alignment.Center) // 정렬은 박스의 정중앙
                .rotate(degree) // 회전 애니메이션 여기서 적용
        )
    }
}


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    ShakeHandViewTheme {
        ShakeHandView()
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment