Member-only story
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.