UGUI 之 LayoutGroup布局

2021-03-10 10:35发布

UGUI Layout布局分为三种:


Horizontal Layout Group(水平布局):对象填充总个父物体,水平会填充


Vertical Layout Group(垂直布局):垂直(高度)会填充


Grid Layout Group (网格布局):以表格的形式布局,不会填充父物体


Grid Layout Group


如果单纯的时候用滑动效果可以使用Scroll Rect组件即可。但使用布局就要使用布局控件


Grid Layout Group是网格布局,


其实滑动依然是用的Scroll Rect。



Spacing 表示 cell之间的距离。

Cell表示格子的宽度和和高度

Start Axis 表示布局方式,有横向和纵向

Child Alignment 表示对齐方式。


注意Layout Group节点下面的所有cell节点都是不能修改Rect Transform的。因为cell可能下面会放很多图片,这样我们会用个空的gameObject来当父节点。

using UnityEngine;

using System.Collections;

using UnityEngine.EventSystems;

using UnityEngine.UI;


public class newScroll : MonoBehaviour, IBeginDragHandler, IEndDragHandler

{

    private ScrollRect rect;

    

    //每页的比列:0/2=0  1/2=0.5  2/2=1

    float[] pages = { 0, 0.5f, 1 };


    //滑动速度

    public float smooting = 4;


    //滑动的起始坐标

    float targethorizontal = 0;


    //是否拖拽结束

    bool isDrag = false;



    void Start()

    {

        rect = transform.GetComponent<ScrollRect>();

    }


    void Update()

    {

        //拖动结束,在进行转换

        if (!isDrag)

        {

            rect.horizontalNormalizedPosition = Mathf.Lerp(rect.horizontalNormalizedPosition, targethorizontal, Time.deltaTime * smooting);

        }

    }


    /// <summary>

    /// 拖动开始

    /// </summary>

    public void OnBeginDrag(PointerEventData eventData)

    {

        isDrag = true;

    }


    /// <summary>

    /// 拖拽结束

    /// </summary>

    public void OnEndDrag(PointerEventData eventData)

    {

        isDrag = false;

        

        float posX = rect.horizontalNormalizedPosition;

        int index = 0;

        //假设离第一位最近

        float offset = Mathf.Abs(page[index] - posX);

        for (int i = 1; i < page.Length; i++)

        {

            float temp = Mathf.Abs(pages[i] - posX);

            if (temp < offset)

            {

                index = i;

                //保存当前的偏移量

                offset = temp;

            }

        }


        targethorizontal = pages[index];

    }

}



————————————————

版权声明:本文为CSDN博主「妳是我改卟了的bug」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/Czhenya/article/details/82887360