How do I draw a line to perfectly align the top of the text?

I can completely align the original line. getLineBounds

will give a baseline that is perfectly aligned with the text (lineBottom - descent). I am using rect.top

as a top line which will give a padded line on top to see the screenshot.

enter image description here

The main problem is that I have different fonts. And this code works fine on some fonts.

This is the code

int baseline = getLineBounds(i, rect);
int topLine =  rect.top;

   canvas.drawLine(rect.left - padding, baseline, rect.right + padding,
                    baseline, paint);

   canvas.drawLine(rect.left - padding, topLine, rect.right + padding, topLine,
                    paint);

   canvas.drawLine(rect.left - padding, (baseline + topLine) / 2, rect.right
                    + padding, (baseline + topLine) / 2, paint1);

      

This is what I have tried.

1) Used "StaticLayout" to get the top line, but doesn't make any difference.

2) Used paint to get the height of the font and add it to the baseline

 paint.setTextSize(getTextSize());
 paint.setTypeface(getCurrentTypFace());
 paint.getTextBounds(getText().toString(), 0, getText().length(), r);
 int height = r.height();
 int topLine = baseline + height;

      

3) Tried with FontPadding = false android:includeFontPadding="false"

So my question is how to get the topline as a baseline. Any help with this is greatly appreciated.

0


source to share


1 answer


Try paint.getTextBounds(...)

again, but use r.top

, (or actually -r.top

) instead r.height

:

paint.setTextSize(getTextSize());
paint.setTypeface(getCurrentTypFace());
paint.getTextBounds(getText().toString(), 0, getText().length(), r);
int ascent = r.top;
int topLine = baseline + ascent;

      

r.height

gives the distance from the very bottom of the character to the very top, whereas it r.top

should give a negative distance from the baseline to the very top.



If that doesn't work either, you just have to draw the text on a temporary canvas in memory and loop through pixels row by row until you find black to measure the ascent yourself.

Make sure you use all caps anyway. If you are using only lowercase text, it will most likely give you the coordinates of the orange dotted line.

Note that both methods will give you the pixel coordinate at the very top edge of the font, not at the center of the stroke. Also, some letters in some fonts can overshoot the coordinates, which you really want to draw quite a bit. Your safest bet is probably to choose a standard line to measure, like capital O

for the blue line and lower case O

for the orange line (unless it's script -font, which squiggle a bit in the upper right corner O

that extends beyond the top of the circle .. .) and then keep a slight offset for each font that tells you how thick the stroke line width is, so your lines go through the top of the letter rather than above it.

+2


source







All Articles