0

I am trying to draw grid of numbers into a canvas.

val textX = x * TILE_SIZE + TILE_SIZE / 2f
val textY = y * TILE_SIZE + TILE_SIZE / 2f 
canvas.drawText(number.toString(), textX, textY, textPaint)

This is my paint

private val textPaint: Paint by lazy {
    Paint().apply {
        isAntiAlias = false
        color = Color.WHITE
        textSize = TILE_SIZE * 0.1f
        textAlign = Paint.Align.CENTER
        style = Paint.Style.FILL
    }
}

But the canvas keeps disjointing my text and aligns it in a non regular grid. I double checked my position values. Is there something I am missing?

enter image description here

edit: I am aware I have alignment set to CENTER, but if you notice, the text in the 4th row has higher offset then in the previous row

I was able to resolve the text disjointing by adding a subPixelText flag, interestingly, when i set paints flag strikeThroughText

isStrikeThruText = true

I get following result:

enter image description here

This, I believe this shows that the coordinates are set properly but there might be some issue with the paint configuration due to the font size.

Martin Rončka
  • 193
  • 2
  • 14

1 Answers1

0

There were two separate issues I have managed to solve:

  1. Text disjointment - this was caused by having very small text, the result was that single letter has sometimes taken up too much space and shifted the next letter. Solution to this is changing paint subpixelText attribute:

    isSubpixelText = true
    
  2. Text misposition - after looking into Paint.FontMetrics I have realized that the ascent and descent values are recommended values set by the font and can be thus changed only within specified paint font. I solved this simply by switching to another font.

Edit: I ended up using StaticLayout, more on the topic here

Martin Rončka
  • 193
  • 2
  • 14