UIPanel自适应管理器

UIPanel自适应管理器

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

/// 
/// UIPanel自适应管理器
/// 
public class UIPanelAdjustMgr
{
    private static UIPanelAdjustMgr instance;
    public static UIPanelAdjustMgr Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new UIPanelAdjustMgr();
            }
            return instance;
        }
    }

    /// 
    /// 弹框Panel自适应(适用于UI Scale Mode为Scale With Screen Size,Screen Match Mode 为Expand的Canvas)
    /// 
    /// 需要进行自适应的弹框
    /// 
    /// 
    /// 
    internal void SetPanelSize(RectTransform elasticFramePanel, Vector2 canvas_Default_Rect_WH, Vector2 panel_Default_Rect_WH, float scale)
    {
        float ratioDefault2H = panel_Default_Rect_WH.y / canvas_Default_Rect_WH.y;
        Vector2 correct_Panel_Rect_WH;
        correct_Panel_Rect_WH.y = elasticFramePanel.parent.GetComponent<RectTransform>().rect.height * ratioDefault2H;
        correct_Panel_Rect_WH.x = correct_Panel_Rect_WH.y * (panel_Default_Rect_WH.x / panel_Default_Rect_WH.y);

        elasticFramePanel.sizeDelta = correct_Panel_Rect_WH * scale;
    }

    /// 
    /// Content大小自适应
    /// 
    /// 
    /// 
    /// 
    /// 缩放比例,保持和弹框Panel一致
    internal void SetContentCellSize(GameObject contentWithGrid, Vector2 panel_Default_Rect_WH, Vector2 default_ContentCellSize, Vector2 panel_Correct_Rect_WH)
    {
        Vector2 correct_ContentCellSize;
        correct_ContentCellSize.x = (panel_Correct_Rect_WH.x / panel_Default_Rect_WH.x) * default_ContentCellSize.x;
        correct_ContentCellSize.y = (panel_Correct_Rect_WH.y / panel_Default_Rect_WH.y) * default_ContentCellSize.y ;

        contentWithGrid.GetComponent<GridLayoutGroup>().cellSize = correct_ContentCellSize;
    }

    /// 
    /// 设置竖向排版GridLayout的Content容器的大小(列表一般是panel打开后动态实例化出来的,如果需要实例化很多个,panel适配完成后直接得到的item数量不一定正确,因此单独出来这个方法)
    /// 
    /// 当前content下的列表的child数量()
    internal void SetContent_H(GameObject content)
    {
        int childCount = content.transform.childCount;
        content.GetComponent<RectTransform>().sizeDelta = new Vector2(0, content.GetComponent<GridLayoutGroup>().cellSize.y * childCount);
    }

    internal void SetContent_W(GameObject content)
    {
        int childCount = content.transform.childCount;
        content.GetComponent<RectTransform>().sizeDelta = new Vector2(content.GetComponent<GridLayoutGroup>().cellSize.x * (childCount - 1), content.GetComponent<GridLayoutGroup>().cellSize.x);
    }
}

你可能感兴趣的:(Unity)