Animating Circle Drawing in Android using Jetpack Compose
In Android, we can create animations of our choice for displaying an entry, in-transit, or exit of an element or a view. The most commonly inbuilt animation is of Circular ProgressBar, where an animator sweeps out a circle indicating the progress of the executed task. A sample video is given below to get an idea about what we are going to do in this article.
In this article, we will show you how you could create such an animation in Android using Jetpack Compose.
Steps to Implement in Animating Circle Drawing
Step 1: Create a New Project in Android Studio
To create a new project in the Android Studio, please refer to How to Create a new Project in Android Studio with Jetpack Compose.
Note: Select Kotlin as the programming language.
Step 2: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
MainActivity.kt:
package com.geeksforgeeks.demo
import android.os.Bundle
import androidx.activity.*
import androidx.activity.compose.setContent
import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.unit.dp
import com.geeksforgeeks.demo.ui.theme.DemoTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
DemoTheme(dynamicColor = false, darkTheme = false) {
Column(
Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
CircleAnimation()
}
}
}
}
}
@Composable
fun CircleAnimation(modifier: Modifier = Modifier) {
// Declaring circle radius
val radius = 200f
// Creating animation
val animateFloat = remember { Animatable(0f) }
LaunchedEffect(animateFloat) {
animateFloat.animateTo(
targetValue = 1f,
animationSpec = tween(
durationMillis = 3000,
easing = LinearEasing
)
)
}
// Creating Arc with useCenter as True
Row {
Canvas(
modifier = Modifier
.width(100.dp)
.height(100.dp)
) {
drawArc(
color = Color.Black,
startAngle = 0f,
sweepAngle = 360f * animateFloat.value,
useCenter = true,
size = Size(radius * 2, radius * 2),
style = Stroke(2.0f)
)
}
}
// Adding a Space of height 100dp
Spacer(modifier = Modifier.height(100.dp))
// Creating Arc with useCenter as False
Row {
Canvas(
modifier = Modifier
.width(100.dp)
.height(100.dp)
) {
drawArc(
color = Color.Black,
startAngle = 0f,
sweepAngle = 360f * animateFloat.value,
useCenter = false,
size = Size(radius * 2, radius * 2),
style = Stroke(2.0f)
)
}
}
}