Created
November 30, 2024 12:14
-
-
Save imandaliya/b93fe56b1ec4c0d161b0ef83b81ce52e to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Thread https://stackoverflow.com/questions/3257293/measuring-text-width-to-be-drawn-on-canvas-android | |
| fun String.getWidth(fontSize: Float): Float { | |
| val textPaint = TextPaint() | |
| textPaint.textSize = fontSize | |
| textPaint.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) | |
| val texts = this.split("\n") | |
| if (texts.size == 1) { | |
| return textPaint.measureText(this) | |
| } | |
| var finalWidth = 0f | |
| for (text in texts) { | |
| val thisLineWidth = text.getWidth(fontSize) | |
| if (thisLineWidth > finalWidth) { | |
| finalWidth = thisLineWidth | |
| } | |
| } | |
| return finalWidth | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment