Tanoda
CanvasSizeFitter.cs
Go to the documentation of this file.
1using System.Collections;
2using System.Collections.Generic;
3using UnityEngine;
4using UnityEngine.UI;
5
6public class CanvasSizeFitter : MonoBehaviour
7{
8 public Text displayText;
9 // Start is called before the first frame update
10 void Start()
11 {
12 if (!string.IsNullOrEmpty(displayText.text))
13 {
14 (displayText.rectTransform.parent as RectTransform).SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, displayText.transform.parent.GetComponent<RectTransform>().rect.width);
15 RecalculateSize();
16 }
17 }
18 private void Update()
19 {
20 (displayText.rectTransform.parent as RectTransform).SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, displayText.transform.parent.GetComponent<RectTransform>().rect.width);
21 RecalculateSize();
22 }
23
24 // Update is called once per frame
25
26
27 internal void RecalculateSize()
28 {
29 (displayText.rectTransform.parent as RectTransform).SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, GetTextSize(displayText).y + 400);
30 }
31 internal Vector2 GetTextSize(Text t)
32 {
33 TextGenerator textGen = new TextGenerator();
34 TextGenerationSettings generationSettings = t.GetGenerationSettings(t.rectTransform.rect.size);
35 float width = textGen.GetPreferredWidth(t.text, generationSettings);
36 float height = textGen.GetPreferredHeight(t.text, generationSettings);
37 return new Vector2(width, height);
38 }
39}