Created
April 27, 2019 14:45
-
-
Save lynzrand/71322cfdccb9f3a3a6e9be8017960c56 to your computer and use it in GitHub Desktop.
Determining a Text's width in characters
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
public static Vector2Int GetConsoleSize(Text text) | |
{ | |
text.font.RequestCharactersInTexture(" ", text.fontSize, text.fontStyle); | |
text.font.GetCharacterInfo(' ', out CharacterInfo info, text.fontSize, text.fontStyle); | |
var scaleFactor = text.canvas.scaleFactor; | |
// Unity requires fonts to be pixel perfect whether the "pixel perfect" | |
// tick is ticked or not in the root canvas | |
float fontWidth = Mathf.Round(info.advance * scaleFactor) / scaleFactor; | |
float fontHeight = Mathf.Round(text.fontSize * text.lineSpacing * scaleFactor) / scaleFactor; | |
var rect = text.GetComponent<RectTransform>().rect; | |
float boundingBoxWidth = rect.xMax - rect.xMin; | |
float boundingBoxHeight = rect.yMax - rect.yMin; | |
int consoleWidth = Mathf.FloorToInt(boundingBoxWidth / fontWidth); | |
int consoleHeight = Mathf.FloorToInt(boundingBoxHeight / fontHeight); | |
if (consoleWidth < 0) consoleWidth = 0; | |
if (consoleHeight < 0) consoleHeight = 0; | |
return new Vector2Int(x: consoleWidth, y: consoleHeight); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment