본문 바로가기
Android Jetpack Compose/Jetpack Compose

IconButton Ripple Effect 구현 # Jetpack Compose

by Developer88 2023. 4. 28.
반응형

기존 XML 의 ImageButton 유아이에 대응되는 것이 바로 IconButton 인데요.

오늘은 이 버튼에 Ripple Effect주는 방법에 대해서 정리해 보도록 하겠습니다.

 

1. IconButton 에 Ripple Effect 주기

1-1. Indication

XML 에서는 ImageButton으로 구현하였던 것들은 대부분 IconButton 으로 변환할 수 있는데요.

먼저 코드를 보겠습니다.

핵심적인 부분이 바로 Modifier.Indication() 부분인데요.

Visual Effect 를 그려주는 부분이 됩니다.

 

IconButton(
    onClick = {},
    modifier = Modifier
        .size(40.dp)
        .indication(interactionSource, ripple)
){
    Image(
        painter = painterResource(id = R.drawable.test),
        contentDescription = "test"
    )
}

 

 

Visual effect를 그려주는 indication 함수를 보면 2개의 인자를 필요로 하는데요.

InteractionSource 와 Indication객체를 넣어주어야 합니다.

 

 

InteractionSource는 아래 코드와 같이 구할 수 있는데요.

이것은 UI요소의 변화를 감지할 수 있도록 해줍니다.

 

val interactionSource = remember { MutableInteractionSource() }

 

1-2. Indication

이제, 남은 것은, Indication 객체인데요.

이제 ripple 효과가 등장할 차례입니다.

ripple효과는 rememberRipple ()함수로 쉽게 가져올 수 있는데요.

 

 

위에 보이는 것처럼, 

ripple 효과의 radius나 퍼지는 부분이 다른 UI에 잘릴 지를 bound로,

radius의 크기등도 지정할 수 있습니다.

Color도 지정할 수 있구요.

return 타입은 우리가 원하는 Indication 타입인 것을 알 수 있습니다.

 

1-3. 구현

정리해서, 코드로 적어보면 다음과 같은 것을 볼 수 있습니다.

 

val interactionSource = remember { MutableInteractionSource() }
val ripple = rememberRipple(bounded = false)

IconButton(
    onClick = {},
    modifier = Modifier
        .size(40.dp)
        .indication(interactionSource, ripple)
        .padding(end = 16.dp)
){
    Image(
        painter = painterResource(id = R.drawable.test_image),
        contentDescription = "testButton"
    )
}

 

 

참고로 위에서 원래 Image의 painterResource의 id 프로퍼티는,

"R.drawable.test"와 같은 식으로 지정하는데요.

추후에 프로그래밍적으로 변동을 줄 때는 위와 같이,

mutableStateOf 타입으로 저장해서 변경해주면 됩니다.

특별히 변동되지 않는 스테틱한 버튼이라면, 

id에 "R.drawable.test"와 같이 넣어주면 됩니다.

 

val imageResource = remember { mutableStateOf(R.drawable.test_image) }

val interactionSource = remember { MutableInteractionSource() }
val ripple = rememberRipple(bounded = false)
IconButton(
    onClick = {},
    modifier = Modifier
        .size(40.dp)
        .indication(interactionSource, ripple)
        .padding(end = 16.dp)
){
    Image(
        painter = painterResource(id = imageResource.value),
        contentDescription = "alarmButton"
    )
}

 

이상으로 Jetpack Compose 에서 IconButton에 Ripple 효과를 주는 방법에 대해서 정리해 보았습니다.

728x90

댓글