How can I get the height of a given string's descender?
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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With