drawBehind , drawWithContent , drawWithCache Modifier In Jetpack Compose
In this article we will see drawBehind
, drawWithContent
and drawWithCache
modifier in Jetpack Compose.
drawBehind Modifier
drawBehind
modifier is very useful . Use it when you want to draw something behind any composable function .
Let’s make this with drawBehind
modifier
Basically we have a Text
and behind this we added a rounded rectangle.
@Composable
fun DrawBehindSomething(
modifier: Modifier
) {
Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(text = stringResource(R.string.hello_world),
modifier = Modifier
.drawBehind {
drawRoundRect(
color = Color.Black,
cornerRadius = CornerRadius(16.dp.toPx(), 16.dp.toPx())
)
}
.padding(horizontal = 30.dp, vertical = 10.dp),
color = Color.White
)
}
}
As you can see the above code , we have used drawBehind
modifier on Text
. drawBehind
takes extension function of DrawScope
. DrawScope
is an interface which provides lot of option to draw behind any composable.
Here we want to draw rounded rectangle , so we called drawRoundRect
and given the color
and cornerRadius
.
drawWithContent Modifier
If you want to draw shape over shape/content then you can use drawWithContent
modifier. Just like Box
composable function
@Composable
fun DrawContentScreen(
modifier: Modifier
) {
Box(
modifier = modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Spacer(modifier = Modifier
.drawWithContent {
drawRoundRect(
color = Color.Black,
cornerRadius = CornerRadius(16.dp.toPx(), 16.dp.toPx())
)
drawCircle(
color = Color.Red
)
}
.size(200.dp))
}
}
As you can see above , in the Spacer
composable function , we called drawWithContent
function , which takes extension function of DrawScope
.
After that we called drawRoundRect
and drawCircle
that will draw over each other.
drawWithCache Modifier
drawWithCache
modifier is used to cache the object until the drawing area changes. it’s good to use when you doing heavy calculation to render something.
@Composable
fun DrawWithCache(
modifier: Modifier
) {
Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center){
Text(
"Hello Compose!",
modifier = Modifier
.drawWithCache {
val brush = Brush.linearGradient(
listOf(
Color(0xFF9E82F0),
Color(0xFF42A5F5)
)
)
onDrawBehind {
drawRoundRect(
brush,
cornerRadius = CornerRadius(10.dp.toPx())
)
}
}.padding(horizontal = 10.dp, vertical = 10.dp)
)
}
}
As you can see above we have called drawWithCache
modifier which take extension function of CacheDrawScope
. Through this we can get onDrawBehind
& onDrawWithContent
.
onDrawBehind
will draw behind the Text.
here the object will be cached until the drawing area changes.
These all modifiers are really useful you can learn more from here.