Draw Text With Canvas In Jetpack Compose.

Jayant Kumar🇮🇳
2 min readMay 3, 2024
Photo by Neven Krcmarek on Unsplash

In this article we will see how to draw Text with Canvas in Jetpack Compose.

I have already written few articles on canvas.

To draw the text, you need two things ,

  • Canvas Composable function
  • drawText() function
@Composable
fun DrawText() {
val textMeasurer = rememberTextMeasurer()
val text = "Hello"
val textLayoutResult = remember(text) {
textMeasurer.measure(text)
}
Canvas(modifier = Modifier.fillMaxSize()) {
val width = size.width
val height = size.height
drawText(
text = text,
textMeasurer = textMeasurer,
topLeft = Offset(
x = width / 2 - textLayoutResult.size.width,
y = height / 2 - textLayoutResult.size.height
),
style = TextStyle(
fontSize = 30.sp,
fontWeight = FontWeight.Bold
)
)
}
}

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

drawText() function takes few parameters -

  • textMeasurewe can measure the width and height of the text.
  • topLeft — it’s the position of the text.
  • style — provide the style of the text.
  • text — provide to show the text.

Now the text will be in the center.

Draw Text Inside Circle


@Composable
fun DrawText() {
val textMeasurer = rememberTextMeasurer()
val text = "Hello"
val textLayoutResult = remember(text) {
textMeasurer.measure(text)
}
Canvas(modifier = Modifier.fillMaxSize()) {
val width = size.width
val height = size.height
drawCircle(
color = Color.Red.copy(alpha = 0.5f),
center = Offset(width / 2, height / 2),
radius = 100.dp.toPx()
)
drawText(
text = text,
textMeasurer = textMeasurer,
topLeft = Offset(
x = width / 2 - textLayoutResult.size.width,
y = height / 2 - textLayoutResult.size.height
),
style = TextStyle(
fontSize = 30.sp,
fontWeight = FontWeight.Bold
)
)
}
}

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 🇮🇳