Draw Rectangle With Canvas In Jetpack Compose.

Jayant Kumar🇮🇳
3 min readJan 8, 2024
Photo by Michele Feola on Unsplash

In this article we will see how to draw a Rectangle shape with Canvas in Jetpack Compose.

You can check my recent articles on

To draw a Rectangle shape , you need of two thing only -

  • Canvas composable function
  • drawRect() function
  Canvas(
modifier = Modifier
.padding(horizontal = 10.dp)
.fillMaxSize()
) {
val width = size.width
val height = size.height
drawRect(
color = Color.Red,
size = Size(width, 300f),
topLeft = Offset(0f, 100f))
}

As you can see above , we called Canvas composable function and given the full size to the screen.

  • we called drawRect() function , where provide color , size of the rectangle and position where it will drawn.
  • topLeft parameter takes Offset(x,y) , if we increase the value x it will move horizontally and if we increase the value of y it will move vertically.

Faded color

use alpha parameter and provide range from 0.1f to 1.0f

drawRect(
color = Color.Red,
size = Size(width, 300f),
topLeft = Offset(0f, 100f),
alpha = 0.3f)

Remove the color and provide border only

  • use style parameter and provide width .
 drawRect(
color = Color.Red,
size = Size(width, 300f),
topLeft = Offset(0f, 100f),
style = Stroke(
width = 10f
))

dashed border

  • use pathEffect parameter and provide dashPathEffect .
 drawRect(
color = Color.Red,
size = Size(width, 300f),
topLeft = Offset(0f, 100f),
style = Stroke(
width = 10f,
pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 25f), 25f)
))

Round corners of Rectangle

To provide round corners of rectangle use drawRoundRect() function.

 Canvas(
modifier = Modifier
.padding(horizontal = 20.dp)
.fillMaxSize()
) {
drawRoundRect(
color = Color.Red,
topLeft = Offset(0f, 100f),
size = Size(size.width, 300f),
cornerRadius = CornerRadius(100f)
)
}

That’s all for today’s my friends , Hope you enjoyed and learnt something new from this article.

--

--

Jayant Kumar🇮🇳

Hello , My name is Jayant, I am a tech youtuber and software Engineer from India 🇮🇳