字體框的寬和背景圖的寬自適應字體的長
即:改變字體的長度,顯示字體的字體框的寬和背景圖的寬也會跟著改變
注:腳本掛載在canvas的image下,字體Text是image的子物體
代碼如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 根據字體的長度,背景圖片的寬度和顯示字體的寬度也會相應改變
/// 掛載在背景圖上
/// </summary>
public class SelfAdaption : MonoBehaviour
{
private Transform font;
private float fontLength;
void Start()
{
font = transform.Find("Text");
fontLength = font.transform.GetComponent<Text>().text.Length;
Debug.Log(fontLength);
//根據字體的長度改變背景圖的長度
//fontLength大于8的時候,每個字占的背景就要小一點
if (fontLength <= 7)
{
//字體
font.GetComponent<RectTransform>().sizeDelta = new Vector2(fontLength * 15, 20f);
//背景
transform.GetComponent<RectTransform>().sizeDelta = new Vector2(fontLength * 15, 20f);
}
else
{
font.GetComponent<RectTransform>().sizeDelta = new Vector2(fontLength * 12.5f, 20f);
transform.GetComponent<RectTransform>().sizeDelta = new Vector2(fontLength * 12.5f, 20f);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/295745.html
標籤:其他
上一篇:Unity之預制體和克隆體