본문 바로가기
안드로이드 코틀린

[Kotlin][Android] Jetpack Compose로 간단한 애니메이션 구현하기

by teamnova 2025. 1. 8.
728x90

 

안녕하세요 

오늘은 Jetpack Compose를 사용하여 간단한 애니메이션을 구현하는 예제를 소개하겠습니다

 

버튼을 클릭할 때 색상과 크기가 부드럽게 변하는 애니메이션을 구현하는 코드입니다 

 


Jetpack Compose는 다양한 animate*AsState 함수를 제공하여 상태 변화에 따른 애니메이션을 쉽게 구현할 수 있도록 도와줍니다

예를 들어 애니메이션의 색상, 단위(크기) 변화, 값 변화, 정수 값 변화, 오프셋(위치) 변화, 사이즈 변화 등 

target 값을 기준으로 현재 값에서 새로운 값으로 자연스럽게 전환되도록 애니메이션을 적용할 수 있습니다 

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AnimatedButtonScreen()
        }
    }
}

@Composable
fun AnimatedButtonScreen() {
    // 버튼의 클릭 상태를 저장하는 변수
    var isClicked by remember { mutableStateOf(false) }

    // 색상 애니메이션
    val backgroundColor by animateColorAsState(
        targetValue = if (isClicked) Color(0xFF6200EE) else Color(0xFF03DAC5),
        animationSpec = tween(durationMillis = 500)
    )

    // 크기 애니메이션
    val size by animateDpAsState(
        targetValue = if (isClicked) 150.dp else 100.dp,
        animationSpec = tween(durationMillis = 500)
    )

    // 중앙에 배치
    Box(
        contentAlignment = Alignment.Center,
        modifier = Modifier.fillMaxSize()
    ) {
        Box(
            modifier = Modifier
                .size(size)
                .background(backgroundColor, shape = MaterialTheme.shapes.medium)
                .clickable { isClicked = !isClicked }, // 클릭 시 상태 변경
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "클릭!",
                color = Color.White,
                style = MaterialTheme.typography.bodyLarge
            )
        }
    }
}

 

위 예제에서는 색상과 크기 변화에 따라 애니메이션이 적용되는 것을 확인하실 수 있습니다 

감사합니다