Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the height of a given string's descender?

Tags:

android

How can I get the height of a given string's descender?

enter image description here

For instance,

  • abc should return 0.
  • abcl should return 0.
  • abcp should return distance from descnder line to baseline.
  • abclp should return distance from descnder line to baseline.

The best I could came out so far is

private int getDecender(String string, Paint paint) {
    // Append "l", to ensure there is Ascender
    string = string + "l";
    final String stringWithoutDecender = "l";

    final Rect bounds = new Rect();
    final Rect boundsForStringWithoutDecender = new Rect();
    paint.getTextBounds(string, 0, string.length(), bounds);
    paint.getTextBounds(stringWithoutDecender, 0, stringWithoutDecender.length(), boundsForStringWithoutDecender);
    return bounds.height() - boundsForStringWithoutDecender.height();
}

However, my code smell is that they are not good enough. Is there any better and faster way?

like image 796
Cheok Yan Cheng Avatar asked Jan 19 '12 05:01

Cheok Yan Cheng


1 Answers

Actually I was looking for the same functionality. It turns out there is much simpler way, you do not even need separate function for that.

If you just call getTextBounds() on a given string, the returned bounding box will already have that information.

For example:

paint.getTextBounds(exampleString1 , 0, exampleString1.length(), bounds);

if (bounds.bottom > 0) Log.i("Test", "String HAS descender");
else Log.i("Test", "String DOES NOT HAVE descender");

Simply saying bounds.top tells you the ascent of the string (it has negative value as Y axis 0 point is at the baseline of the string) and bounds.bottom tells you the descent of the string (which can be 0 or positive value for strings having descent).

like image 155
MariuszS Avatar answered Nov 14 '22 23:11

MariuszS