前言
用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
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?