Calculate font width and text component adaptation

Time:2021-9-19

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ChatView : MonoBehaviour
{

#region RectTransform
private RectTransform ChatContent;
#endregion

#region GameObject
private GameObject LeftChatObj;
private GameObject RightChatObj;
#endregion

private void Awake()
{
    InitGetComponent();
}

private void Start()
{
    Test();
}

private void InitGetComponent()
{
    #region RectTransform
    ChatContent = transform.Find("ChatPanel/ScrollView/Viewport/ChatContent").GetComponent();
    #endregion

    #region GameObject
    LeftChatObj = Resources.Load("Info/LeftChatInfo");
    RightChatObj = Resources.Load("Info/RightChatInfo");
    #endregion
}

//Test method
private void Test()
{
    ChatInfo info1 = Instantiate(LeftChatObj, ChatContent).GetComponent();
    ChatInfo info2 = Instantiate(RightChatObj, ChatContent).GetComponent();
    //
    Info1. Setchattext ("chair in a foreign land, leaves have wings, chair in a foreign land, leaves have wings, chair in a foreign land, leaves have wings");
    Info2. Setchattext ("we are like a rainbow, we know it when we meet the top, we are like a rainbow, we know it when we meet the top, we are like a rainbow, we know it when we meet the top, we are like a rainbow, we know it when we meet the top, we are like a rainbow, we know it when we meet the top");
    UpdateLayout();
}

private void UpdateLayout()
{
    UITools.Instance.UpdateLayout(ChatContent);
}

}

public class ChatInfo : MonoBehaviour
{

#region RectTransform
private RectTransform RtChatContentText;
private RectTransform RtBgEmpty;
private RectTransform RtContentEmpty;
private RectTransform RtSelf;
#endregion

#region Text
private Text ChatContentText;
#endregion

#region float
//Total width and height of font
private float m_FontTotalWidth = 0f;
private float m_FontTotalHeight = 0f;
//Width and height of text
private float m_TextWidth = 0f;
private float m_TextHeight = 0f;
//Text background width and height
private float m_TextBgWidth = 0f;
private float m_TextBgHeight = 0f;
#endregion


private void Awake()
{
    InitGetComponent();
}

private void Start()
{
    //Setchattext ("chair in a foreign country, leaves have wings. Chair in a foreign country, leaves have wings. Chair in a foreign country, leaves have wings. Chair in a foreign country, leaves have wings. Chair in a foreign country, leaves have wings. Chair in a foreign country, leaves have wings.");
    //Setchattext ("the chair is in a foreign land, and the leaves have wings");
}


private void InitGetComponent()
{
    #region RectTransform
    RtChatContentText = transform.Find("ContentEmpty/BgEmpty/ChatContentText").GetComponent();
    RtBgEmpty = transform.Find("ContentEmpty/BgEmpty").GetComponent();
    RtContentEmpty = transform.Find("ContentEmpty").GetComponent();
    RtSelf = transform.GetComponent();
    #endregion

    #region Text
    ChatContentText = transform.Find("ContentEmpty/BgEmpty/ChatContentText").GetComponent();
    #endregion
}


/// 
///Set up chat content
/// 
public void SetChatText(string str)
{
    ChatContentText.text = str;
    CalculateSize();
    UpdateLayout();
}

//Calculate and set text size
private void CalculateSize()
{
    string str = ChatContentText.text;
    TextGenerator generator = ChatContentText.cachedTextGenerator;
    TextGenerationSettings textSetting = ChatContentText.GetGenerationSettings(Vector2.zero);
    //Total width and height of font
    m_FontTotalWidth = generator.GetPreferredWidth(str, textSetting);
    m_FontTotalHeight = generator.GetPreferredHeight(str, textSetting);

    IList tempList = generator.characters;
    //Calculate a new line. This method can effectively calculate whether the width of the last text in the line needs to be calculated into the width statistics of the next line
    float tempWidth = 0;
    int newLine = 0;
    for (int i = 0; i < tempList.Count; i++)
    {
        tempWidth += tempList[i].charWidth;
        if (tempWidth > 240f)
        {
            tempWidth = tempList[i].charWidth;
            newLine += 1;
        }
    }
    //Get text width and height
    m_TextWidth = RtChatContentText.rect.width;
    m_TextHeight = RtChatContentText.rect.height;
    //Gets the width and height of the BG background image (text parent) of text
    m_TextBgWidth = RtBgEmpty.rect.width;
    m_TextBgHeight = RtBgEmpty.rect.height;
    //Update text height
    m_TextHeight += newLine * 22f;
    RtChatContentText.sizeDelta = new Vector2(m_TextWidth, m_TextHeight);
    //Update text BG height
    m_TextBgHeight += newLine * 22f;
    RtBgEmpty.sizeDelta = new Vector2(m_TextBgWidth, m_TextBgHeight);
}

//Refresh layout
private void UpdateLayout()
{
    UITools.Instance.UpdateLayout(RtContentEmpty, RtSelf);
}

}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UITools : Singleton
{

public void UpdateLayout(params RectTransform[] rects)
{
    for (int i = 0; i < rects.Length; i++)
    {
        LayoutRebuilder.ForceRebuildLayoutImmediate(rects[i]);
    }
}

}