Draw Rectangle With Canvas In Jetpack Compose.
3 min readJan 8, 2024
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 functiondrawRect()
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 providecolor
,size
of the rectangle andposition
where it will drawn. topLeft
parameter takesOffset(x,y)
, if we increase the valuex
it will move horizontally and if we increase the value ofy
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 providewidth
.
drawRect(
color = Color.Red,
size = Size(width, 300f),
topLeft = Offset(0f, 100f),
style = Stroke(
width = 10f
))
dashed border
- use
pathEffect
parameter and providedashPathEffect
.
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.