Draw Text With Canvas In Jetpack Compose.
2 min readMay 3, 2024
In this article we will see how to draw Text with Canvas in Jetpack Compose.
I have already written few articles on canvas.
- Draw Line With Canvas
- Draw Circle With Canvas
- Draw Rectangle With Canvas
- Draw an arc With Canvas
- Draw an oval with Canvas
To draw the text, you need two things ,
Canvas
Composable functiondrawText()
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 -
textMeasure
— we 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.