Skip to content

Instantly share code, notes, and snippets.

@nikhil-mandlik-dev
Created September 29, 2022 12:23
Show Gist options
  • Save nikhil-mandlik-dev/b413893fc8643685437d6f79350a56d5 to your computer and use it in GitHub Desktop.
Save nikhil-mandlik-dev/b413893fc8643685437d6f79350a56d5 to your computer and use it in GitHub Desktop.
Translating Objects along a path
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val infiniteTransition = rememberInfiniteTransition()
val progress by infiniteTransition.animateFloat(
initialValue = 0f,
animationSpec = infiniteRepeatable(
animation = tween(2000),
repeatMode = RepeatMode.Restart
),
targetValue = 1f
)
Column(
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Canvas(
modifier = Modifier
.fillMaxWidth(fraction = 0.8f)
.fillMaxHeight(fraction = 0.5f)
) {
// Start & End Points
val start = Offset(0f, size.height / 2)
val end = Offset(size.width, size.height / 2)
// Control Points
val c1 = Offset(size.width / 4, 0f)
val c2 = Offset(3 * size.width / 4, size.height)
val c3 = Offset(3 * size.width / 4, 0f)
val c4 = Offset(size.width / 4, size.height)
val infinityPath = Path().apply {
// Move to Start Position
moveTo(start.x, start.y)
// first curve : start -> c1 -> c2 -> end
cubicTo(
c1.x, c1.y,
c2.x, c2.y,
end.x, end.y
)
// Second curve : end -> c3 -> c4 -> start
cubicTo(
c3.x, c3.y,
c4.x, c4.y,
start.x, start.y
)
// Close the Path
close()
}
drawPath(
path = infinityPath,
color = Color.Black,
style = Stroke(width = 1.dp.toPx()),
)
val pos = FloatArray(2)
val tan = FloatArray(2)
PathMeasure().apply {
setPath(infinityPath.asAndroidPath(), false)
getPosTan(length * progress, pos, tan)
}
drawCircle(
radius = 10.dp.toPx(),
color = Color.Blue,
center = Offset(pos[0], pos[1])
)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment