栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > 其他

Unity 背景图片自适应Text长度

其他 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity 背景图片自适应Text长度

前言

用Unity自带插件也可以实现同样效果,可以参考这篇文章。不过封装成脚本使用更方便,而且可以同时添加多个对象。

效果

使用方法

给Text组件挂上UIChildSizeMgr脚本和ContentSizeFitter组件,设置如图所示,文字图片对齐方向调整锚点即可。一个Text组件可以关联多个对象,具体参数根据需求调配。

代码
using System;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Text;
using UnityEngine;

[ExecuteInEditMode]
public class UIChildSizeMgr : UIBehaviour
{
    public FollowItem[] follows;
    private bool bChange = true;

    [Serializable]
    public class FollowItem
    {
        public RectTransform follower;
        public RectOffset padding;
        public bool followWidth = true;
        public bool followHeight = true;

        public void SetSize(RectTransform trans)
        {
            if (null == trans || null == follower)
                return;
            if (followWidth)
            {
                float width = padding.left + padding.right + trans.rect.width;
                follower.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, width);
            }
            if (followHeight)
            {
                float height = padding.top + padding.bottom + trans.rect.height;
                follower.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height);
            }
        }

    }

    protected override void Awake()
    {
        base.Awake();
        bChange = true;
        ResetSize();
    }


    void ResetSize()
    {
        if (!bChange) return;
        RectTransform rectTrans = transform as RectTransform;

        if (null == follows) return;
        for (int i = 0, max = follows.Length; i < max; i++)
        {
            follows[i].SetSize(rectTrans);
        }
       
        bChange = false;
    }

    protected override void OnEnable()
    {
        base.OnEnable();
        bChange = true;
        ResetSize();
    }

    protected override void OnRectTransformDimensionsChange()
    {
        bChange = true;
        ResetSize();
    }

#if UNITY_EDITOR
    void Update()
    {
        if (!Application.isPlaying)
        {
            bChange = true;
            ResetSize();
        }
    }
#endif
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/902305.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号