1

I am drawing Circle and Text on Canvas in jetpack compose. I draw it without any problem through coordinate of Canvas. When I place the circle on start side of Text it too far away. It look like this way

enter image description here

I tried this piece of code

@OptIn(ExperimentalTextApi::class)
@Preview(showBackground = true)
@Composable
fun CanvasView() {
    val textMeasurer = rememberTextMeasurer()
    val textToDraw = "Lab Return"
    val style = TextStyle(
        fontSize = 16.sp,
        color = Color.Black,
    )
    val textLayoutResult = remember(textToDraw) {
        textMeasurer.measure(textToDraw, style)
    }
    Canvas(modifier = Modifier.fillMaxSize()) {
        drawText(
            textMeasurer = textMeasurer,
            text = textToDraw,
            style = style,
            topLeft = Offset(
                x = center.x - textLayoutResult.size.width / 2,
                y = center.y - textLayoutResult.size.height / 2,
            )
        )

        drawCircle(
            color = Color.Gray,
            radius = 6.dp.toPx(),
            center = Offset(center.x / 2, center.y)
        )
    }
}

I want Circle and Text with distance 15.dp. Something like below image

enter image description here

Kotlin Learner
  • 3,995
  • 6
  • 47
  • 127
  • 1
    have you tried to change the X coordinate here: center = Offset(center.x / 2, center.y)? try this: center = Offset(center.x - textLayoutResult.size.width / 2 - with(LocalDensity.current) { 15.dp.toPx() }, center.y) – easy_breezy May 01 '23 at 13:07

1 Answers1

1

You can adjust the x coordinate of the Offset passed to drawCircle by subtracting the radius of the circle and the desired distance (which is as you described 15 dp):

drawCircle(
    color = Color.Gray,
    radius = 6.dp.toPx(),
    center = Offset(
        center.x - textLayoutResult.size.width / 2 - 6.dp.toPx() - 15.dp.toPx(),
        center.y
    )
)
Mikhail Guliaev
  • 1,168
  • 1
  • 6
  • 14