Created
September 9, 2024 11:31
-
-
Save imandaliya/477accfb4f3073a1a1021d54801bc320 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// original link https://chrisbanes.me/posts/measuring-text/ | |
public void drawTextOnCenterOfBounds() { | |
int mTextWidth, mTextHeight; // Our calculated text bounds | |
Paint mTextPaint = new Paint(); | |
// Now lets calculate the size of the text | |
Rect textBounds = new Rect(); | |
mTextPaint.getTextBounds(mText, 0, mText.length(), textBounds); | |
mTextWidth = mTextPaint.measureText(mText); // Use measureText to calculate width | |
mTextHeight = textBounds.height(); // Use height from getTextBounds() | |
// Later when you draw... | |
canvas.drawText(mText, // Text to display | |
mBounds.centerX() - (mTextWidth / 2f), | |
mBounds.centerY() + (mTextHeight / 2f), | |
mTextPaint | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment