Created
February 3, 2024 18:02
-
-
Save ardakazanci/ce58a6af139e4420100f0cab9a78cdb7 to your computer and use it in GitHub Desktop.
Spring Animation for Canvas Drawing Star
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Composable | |
fun SpringAnimationForStar() { | |
var touchPointActions by remember { mutableStateOf(listOf<Offset>()) } | |
var animatedStars by remember { mutableStateOf(listOf<Animatable<Offset, AnimationVector2D>>()) } | |
LaunchedEffect(touchPointActions) { | |
if (touchPointActions.size > 1) { | |
val startPoint = touchPointActions[touchPointActions.size - 2] | |
val endPoint = touchPointActions.lastOrNull() | |
animatedStars += Animatable(startPoint, Offset.VectorConverter).also { animatable -> | |
launch { | |
endPoint?.let { | |
animatable.animateTo( | |
targetValue = it, | |
animationSpec = spring( | |
dampingRatio = Spring.DampingRatioMediumBouncy, | |
stiffness = Spring.DampingRatioNoBouncy) | |
) | |
} | |
} | |
} | |
} | |
} | |
Box(modifier = Modifier | |
.fillMaxSize() | |
.pointerInput(Unit) { | |
detectTapGestures { offset -> | |
touchPointActions += offset | |
} | |
} | |
) { | |
Canvas(modifier = Modifier.fillMaxSize()) { | |
for (i in 1 until touchPointActions.size) { | |
drawLine( | |
start = touchPointActions[i - 1], | |
end = touchPointActions[i], | |
color = Color.Gray, | |
strokeWidth = 10f, | |
pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f) | |
) | |
} | |
animatedStars.forEach { animatable -> | |
starDrawing(center = animatable.value, outerRadius = 100f, innerRadius = 40f) | |
} | |
} | |
} | |
} | |
fun DrawScope.starDrawing(center: Offset, outerRadius: Float, innerRadius: Float) { | |
val path = Path() | |
val numPoints = 5 | |
val angleInc = 360 / (numPoints * 2).toFloat() | |
var currentAngle = -90f | |
for (i in 0 until numPoints * 2) { | |
val radius = if (i % 2 == 0) outerRadius else innerRadius | |
val x = center.x + radius * cos(Math.toRadians(currentAngle.toDouble())).toFloat() | |
val y = center.y + radius * sin(Math.toRadians(currentAngle.toDouble())).toFloat() | |
if (i == 0) path.moveTo(x, y) else path.lineTo(x, y) | |
currentAngle += angleInc | |
} | |
val gradient = Brush.radialGradient( | |
colors = listOf(Color.Black, Color.DarkGray), | |
center = center, | |
radius = outerRadius | |
) | |
path.close() | |
drawPath(path, brush = gradient) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment