- Home /
Question by
Jejkobb · May 13, 2019 at 05:58 PM ·
c#uiuser interfacepanel
How do I get the width and height of text then apply it to a UI panel?
What I'm trying to achieve is like a background for subtitles, that fit the text perfectly. I have a panel and a text object, I made a textBackground script in the panel and referenced the textObject. So I have already tried doing this with localScale, but doesn't feel reliable. I'd like to just get the exact pixel width and height of text and make it so the panel fits perfectly in behind that. This is the script I have now, but the width and height values are really high from the text? And when applied to the panel it's huge, way bigger than the text. I'm guessing preferredWidth and height are the wrong type of value? Can I convert them in a convenient way? Is there a better way to do this?
using UnityEngine;
using UnityEngine.UI;
public class TextBackground : MonoBehaviour
{
public Text textObj;
private RectTransform r;
// Start is called before the first frame update
void Start()
{
r = GetComponent<RectTransform>();
}
// Update is called once per frame
void Update()
{
TextGenerator textGen = new TextGenerator();
TextGenerationSettings generationSettings = textObj.GetGenerationSettings(textObj.rectTransform.rect.size);
float width = textGen.GetPreferredWidth(textObj.text, generationSettings);
float height = textGen.GetPreferredHeight(textObj.text, generationSettings);
r.position = textObj.rectTransform.position;
r.sizeDelta = new Vector2(width, height);
}
}
Comment