0

I need to draw a text without paddings to fill all free space of the box.

The sample code is:

@Composable
fun NumberBox(
    number: Int,
    modifier: Modifier = Modifier,
    color: Color = Color.Unspecified,
    fontStyle: FontStyle? = null,
    fontWeight: FontWeight? = null,
    fontFamily: FontFamily? = null,
    textDecoration: TextDecoration? = null,
    textAlign: TextAlign? = null,
    style: TextStyle = LocalTextStyle.current
) {

    val mergedStyle = style.merge(
        TextStyle(
            color = color,
            fontSize = 40.sp,
            fontWeight = fontWeight,
            textAlign = textAlign,
            fontFamily = fontFamily,
            textDecoration = textDecoration,
            fontStyle = fontStyle,
            platformStyle = PlatformTextStyle(includeFontPadding = false),
        )
    )

    val measurer = rememberTextMeasurer()

    val result = measurer.measure(
        number.toString(),
        style = mergedStyle,
        maxLines = 1,
    )

    Canvas(modifier = modifier, onDraw = {
        //drawText(measurer, text = size.toString())
        //drawText(measurer, text = result.size.height.toString())

        scale(1.8f) {
            translate(
                left = center.x - result.size.width / 2,
                top = center.y - result.size.height / 2
            ) {
                drawText(
                    textLayoutResult = result,
                    color = Color.Blue,
                )
                drawLine(
                    color = Color.Green,
                    start = Offset(0f, result.firstBaseline),
                    end = Offset(size.width, result.firstBaseline),
                )
                drawRect(
                    color = Color.Red,
                    size = result.size.toSize(),
                    style = Stroke()
                )
            }
        }
    })
}

The result of execution is:

enter image description here

The red box is measured text size. I need to draw text without paddings. How to do it?

The required result is:

enter image description here

Viacheslav Smityukh
  • 5,652
  • 4
  • 24
  • 42

1 Answers1

0

I have not found solution for this issue. The paint.getTextBounds is the closest solution but it doesn't satisfy me.

My final solution is:

  1. In case of composable name is the NumberBox I need only digit glyphs.
  2. Open required font in FontForge and save digits as SVG.
  3. Open SVG in Krita and remove extra paddings.
  4. Import SVG as vector assets in the android project.
  5. Render digits as vector images.

The final solution do exactly what I need. Unfortunately this is not applicable to render anything except numbers.

Viacheslav Smityukh
  • 5,652
  • 4
  • 24
  • 42