您当前的位置: 首页 >  unity
  • 3浏览

    0关注

    193博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Unity 背景图片自适应Text长度

我寄人间雪满头丶 发布时间:2022-02-17 09:25:31 ,浏览量:3

前言

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

效果

请添加图片描述

使用方法

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

代码
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             
关注
打赏
1648518768
查看更多评论
0.0582s