Skip to content


[Badge] Center badge content more correctly
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 519835048
  • Loading branch information
imhappi authored and pekingme committed Mar 28, 2023
1 parent 8105cb7 commit fc0de1b
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion lib/java/com/google/android/material/badge/
Expand Up @@ -1077,10 +1077,19 @@ private void drawText(Canvas canvas) {
Rect textBounds = new Rect();
String badgeText = getBadgeText();
textDrawableHelper.getTextPaint().getTextBounds(badgeText, 0, badgeText.length(), textBounds);

// The text is centered horizontally using Paint.Align.Center. We calculate the correct
// y-coordinate ourselves using textbounds.exactCenterY, but this can look askew at low
// screen densities due to canvas.drawText rounding the coordinates to the nearest integer.
// To mitigate this, we round the y-coordinate following these rules:
// If the badge.bottom is <= 0, the text is drawn above its original origin (0,0) so
// we round down the y-coordinate since we want to keep it above its new origin.
// If the badge.bottom is positive, we round up for the opposite reason.
float exactCenterY = badgeCenterY - textBounds.exactCenterY();
badgeCenterY + textBounds.height() / 2,
textBounds.bottom <= 0 ? (int) exactCenterY : Math.round(exactCenterY),

Expand Down

0 comments on commit fc0de1b

Please sign in to comment.