Skip to content

Instantly share code, notes, and snippets.

@lynzrand
Created April 27, 2019 14:45
Show Gist options
  • Save lynzrand/71322cfdccb9f3a3a6e9be8017960c56 to your computer and use it in GitHub Desktop.
Save lynzrand/71322cfdccb9f3a3a6e9be8017960c56 to your computer and use it in GitHub Desktop.
Determining a Text's width in 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