Jetpack Compose Canvas: 10 Practical Examples
<p>Jetpack Compose is revolutionizing the way we build user interfaces on Android. One of the many features it offers is the Canvas API, which allows developers to draw custom shapes, paths, and graphics. In this blog post, we will explore 10 practical examples of using the Canvas API in Jetpack Compose.</p>
<h1>1. Drawing a Circle</h1>
<p>Let’s start with something simple — drawing a circle.</p>
<pre>
@Composable
fun DrawCircle() {
Canvas(
modifier = Modifier
.size(200.dp)
.background(Color.White)
.border(2.dp, color = Color.Blue)
) {
drawCircle(color = Color.Red, radius = 100f)
}
}</pre>
<p><img alt="" src="https://miro.medium.com/v2/resize:fit:396/1*d0EryprxvgH5M0XMAmVmqw.png" style="height:452px; width:440px" /></p>
<h1>2. Drawing a Rectangle</h1>
<p>Drawing a rectangle is just as straightforward.</p>
<pre>
@Composable
fun DrawRectangle() {
Canvas(
modifier = Modifier
.size(200.dp)
.background(Color.White)
.border(2.dp, color = Color.Blue)
) {
drawRect(color = Color.Green, size = size)
}
}</pre>
<p><img alt="" src="https://miro.medium.com/v2/resize:fit:461/1*yemq-Z_R_aco3fTQoVhsvg.png" style="height:512px; width:512px" /></p>
<h1>3. Drawing a Line</h1>
<p>Drawing a line requires two points: a start point and an end point.</p>
<pre>
@Composable
fun DrawLine() {
Canvas(
modifier = Modifier
.size(200.dp)
.background(Color.White)
.border(2.dp, color = Color.Red)
) {
drawLine(
color = Color.Blue,
start = Offset.Zero,
end = Offset(size.width, size.height),
strokeWidth = 4f
)
}
}</pre>
<p><a href="https://medium.com/@andkemal/jetpack-compose-canvas-10-practical-examples-532d40ed3dd0">Click Here</a></p>