Skip to content

Instantly share code, notes, and snippets.

@loloof64

loloof64/Animation.kt

Last active Feb 9, 2021
Embed
What would you like to do?
Jetpack compose alpha 11 : Simple yellow ball running in a red background [Both finite and infinite versions]
import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import android.graphics.Color as LegacyColor
enum class RunStates {
INITIAL, FINAL
}
@Composable
fun YellowBallOnRedBackground(ballX: Float, modifier: Modifier = Modifier) {
return Canvas(
modifier = modifier
.size(width = 300.dp, height = 50.dp)
.background(Color(LegacyColor.RED))
) {
drawCircle(
color = Color(LegacyColor.YELLOW),
radius = 20.dp.toPx(),
center = Offset(ballX, 25.dp.toPx())
)
}
}
@Composable
fun YellowBallRunning(modifier: Modifier = Modifier) {
val xState = remember { MutableTransitionState(RunStates.INITIAL) }
xState.targetState = RunStates.FINAL
val transition = updateTransition(xState)
val x by transition.animateFloat(
transitionSpec = {
when {
RunStates.INITIAL isTransitioningTo RunStates.FINAL -> {
tween(durationMillis = 1000)
}
else -> {
snap()
}
}
}
) { state ->
when (state) {
RunStates.INITIAL -> 60f
RunStates.FINAL -> 450f
}
}
return YellowBallOnRedBackground(ballX = x)
}
@Composable
fun YellowBallRunningInfinite() {
val infiniteTransition = rememberInfiniteTransition()
val x by infiniteTransition.animateFloat(
initialValue = 60f,
targetValue = 450f,
animationSpec = infiniteRepeatable(
animation = tween(1000),
repeatMode = RepeatMode.Restart
)
)
return YellowBallOnRedBackground(ballX = x)
}
@Preview
@Composable
fun YellowBallRunningPreview() {
return YellowBallRunning()
}
@Preview
@Composable
fun YellowBallRunningInfinitePreview() {
return YellowBallRunningInfinite()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment