Skip to content

Commit fc0de1b

Browse files
imhappipekingme
authored andcommitted
[Badge] Center badge content more correctly
PiperOrigin-RevId: 519835048
1 parent 8105cb7 commit fc0de1b

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

lib/java/com/google/android/material/badge/BadgeDrawable.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1077,10 +1077,19 @@ private void drawText(Canvas canvas) {
10771077
Rect textBounds = new Rect();
10781078
String badgeText = getBadgeText();
10791079
textDrawableHelper.getTextPaint().getTextBounds(badgeText, 0, badgeText.length(), textBounds);
1080+
1081+
// The text is centered horizontally using Paint.Align.Center. We calculate the correct
1082+
// y-coordinate ourselves using textbounds.exactCenterY, but this can look askew at low
1083+
// screen densities due to canvas.drawText rounding the coordinates to the nearest integer.
1084+
// To mitigate this, we round the y-coordinate following these rules:
1085+
// If the badge.bottom is <= 0, the text is drawn above its original origin (0,0) so
1086+
// we round down the y-coordinate since we want to keep it above its new origin.
1087+
// If the badge.bottom is positive, we round up for the opposite reason.
1088+
float exactCenterY = badgeCenterY - textBounds.exactCenterY();
10801089
canvas.drawText(
10811090
badgeText,
10821091
badgeCenterX,
1083-
badgeCenterY + textBounds.height() / 2,
1092+
textBounds.bottom <= 0 ? (int) exactCenterY : Math.round(exactCenterY),
10841093
textDrawableHelper.getTextPaint());
10851094
}
10861095

0 commit comments

Comments
 (0)