Animation has always been my absolute favourite. Today, we will cover how to do a nice gradient border animation in Jetpack Compose. In this article, I’ll walk you through the thinking process, which is crucial so you can do similar things independently. Simply reviewing the accompanying images will suffice to kickstart your logic. The final result will be something like this.

So, let’s begin…

Before we jump into actual code, think about how it will be done. Before animating, you need a rounder corner shape with a border. You will be thinking about the RoundedCorner() shape we can pass as a parameter, and it’s done. Imagine we’re working with a limited canvas where we can only draw basic shapes. How would we draw a border around a simple rectangle? Just think for a moment…

The solution lies in using fundamentals…

Yeah, I’ll draw a rounder corner rectangle. Then..

Then, draw another rectangle with a different colour, with a slight padding. Cool, let’s draw

val colorBg = Color(0xFF2C3141)

Canvas(modifier = Modifier.fillMaxWidth().height(200.dp).background(colorBg)) {
drawRoundRect(
color = Color.White,
cornerRadius = CornerRadius(x = 20.dp.toPx(), y = 20.dp.toPx())
)

drawRoundRect(
color = colorBg,
topLeft = Offset(1.dp.toPx(), 1.dp.toPx()),
size = Size(
width = size.width - 2.dp.toPx(),
height = size.height - 2.dp.toPx()
),
cornerRadius = CornerRadius(
x = 19.dp.toPx(),
y = 19.dp.toPx()
)
)
}

This will draw two rounded rectangles on top of each other. The second one will be drawn from a slight offset, which equals border thickness, and we will get the following result.

Good, we’re doing well so far. Next, how will we manage to draw a gradient border? Hmm.. think..

Yeah, I’ll draw the outer rectangle with a gradient brush. Then inner rectangle… Easy as pie, right?

Source link