- Home /
How do I calculate how big text is in a world space canvas UI Text?
I have a Canvas (Render Mode = "World Space", and its Rect Transform has Width = 4, Height = 2) with a Canvas Scaler with "Dynamic Pixels Per Unit" = 20. I have placed a UI Text in the canvas, and would like to know how large in absolute terms the text is in the virtual space. The text is set to Font Size = 12.
How should I calculate the absolute size of the text?
I am not sure I understand the relationship between the dynamic pixels per unit, the font size, the canvas size, and the absolute size of the text. Any help would be greatly appreciated.
Answer by cardcastleusa · Mar 20, 2018 at 04:26 PM
@benjaminoutram The Following Code adjust the height of the text GameObject only! If you need to adjust the parent you will add the heightChange to the parents RectTransform too.
public class Example : MonoBehaviour {
public GameObject text;
public float wordWrapSpacing;
public void AdjustSize()
{
GUIStyle gui = new GUIStyle();
RectTransform textRect = text.getComponent<RectTransform>();
//This calculates the size needed to hold all of the text based on Font Size
Vector2 adjustmentSize = gui.CalcSize(text.getComponent<Text>().text);
//Adjust the wordWrapSpacing based on the font you are using.
float heightChange = size.y * (size.x / textRect.rect.width) + wordWrapSpacing * (size.x / textRect.rect.width);
//This is needed because your text might not have to be adjusted.
if(textRect.rect.height < heightChange)
{
textRect.sizeDelta = new Vector2(textRect.rect.width, textRect.rect.height + heightChange);
}
}//End Function
}//end Class
//Note If you are messing with both height and width you will need to multiply the wordWrapSpacing by the percentage change that has occurred width wise.
This is a very manual way of doing this and unity has many built in functions.
Text.text is not a GUIContent and thus can't be passed into GUIStyle.CalcSize(), which makes this whole thing not work.
Answer by shieldgenerator7 · Jan 04, 2019 at 06:56 AM
I know it's not exact, but this works for me for finding a rough size of GUI text:
static float getTextWidth(Canvas canvas, Text text, int length)
{
return text.fontSize * 0.5f * length * canvas.transform.localScale.x;
}
static float getTextHeight(Canvas canvas, Text text)
{
return text.fontSize * canvas.transform.localScale.y;
}
Your answer
Follow this Question
Related Questions
Moving 3D Text 1 Answer
UI Relative to screen size 1 Answer
How to make parent UI element change size to fit children? 0 Answers
UI Text: Wrap and Expand to keep aspect ratio 2 Answers
How to get the current "best fit" size of a Text component? 3 Answers