-
-
Save lynzrand/31bcbc9e5e5c248e54692158e6ab364e to your computer and use it in GitHub Desktop.
Wrong Code - 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; | |
float fontWidth = info.advance; | |
float fontHeight = text.fontSize * text.lineSpacing; | |
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