记一次Unity_UGUI入门

好吧,写了那么多年Unity,

发现自己还是什么都不会

参考:

自动生成代码(前)

Unity UI代码自动生成 - 盘子脸 - 博客园 (cnblogs.com)

UI动画

Unity进阶技巧 - 动态创建UGUI - 简书 (jianshu.com)

UI边界Bounds

假如有1个UI

下面有2个UIImage

是可以计算子节点的区域大小的

只要在第一个UI节点添加脚本,

[ExecuteInEditMode]
public class BoundsManager : MonoBehaviour
{
    GameObject _tempObject;
    private Canvas _canvas;
    void OnEnable()
    {
        if(_tempObject==null)
        {
           _tempObject = new GameObject("TEMP");
           _tempObject.AddComponent<Image>();
        }
        var rect = transform.GetComponent<RectTransform>();
        _canvas = rect.GetComponentInParent<Canvas>();
        _tempObject.transform.SetParent(_canvas.transform,false);
        
//uNITY 提供的关键方法
        var bounds = RectTransformUtility.CalculateRelativeRectTransformBounds(_canvas.GetComponent<RectTransform>(), rect);


        var targetRect = _tempObject.GetComponent<RectTransform>();
        SetAnchorMiddleCenter(targetRect);
        //targetRect.anchorMin = new Vector2(bounds.min.x,bounds.min.y);
        //targetRect.anchorMax = new Vector2(bounds.max.x, bounds.max.y);
        targetRect.sizeDelta = bounds.size;
        targetRect.anchoredPosition = bounds.center;
    }
    
    public static void SetAnchorMiddleCenter(RectTransform rectTransform){
    

        rectTransform.offsetMin = new Vector2(0.5f, 0.5f);//好像是不对的,哈哈哈
        rectTransform.offsetMax = new Vector2(0.5f, 0.5f);
        rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
        rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
    }


    
}

计算锚点中心

        public static Vector2 ToCenterPivot(RectTransform rect,Vector2 srcPos)
        {
            //设:p1==原点;p2==最终我们要的目标点
            //公式:p1+p=p2
            var pWidth = (rect.sizeDelta.x ) * (rect.pivot.x-0.5f);
            var pHeight = (rect.sizeDelta.y ) * (rect.pivot.y-0.5f);
            
            Vector2 nodeOffset = Vector2.zero;
            if (rect.parent != null)
            {
//                //anchor和父节点有关
                var parentSize = rect.parent.GetComponent<RectTransform>().sizeDelta;
                var x = (0.5f-(rect.anchorMin.x+(rect.anchorMax.x - rect.anchorMin.x) / 2)) * parentSize.x;
                var y = (0.5f-(rect.anchorMin.y+(rect.anchorMax.y - rect.anchorMin.y) / 2)) * parentSize.y;
                
                nodeOffset =new Vector2(x,y);
            }

            return srcPos + new Vector2(pWidth, pHeight) + nodeOffset;
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

avi9111

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值