hch
9 天以前 f99dd641fb1eb7ba7cbeab5b763d26a7324315c7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using UnityEngine;
 
[ExecuteAlways]
[RequireComponent(typeof(RectTransform))]
public class SafeAreaUI : MonoBehaviour
{
 
    public const int SafeWidth = 75;
    public const int SafeBottom = 15;   //竖屏下方间隔
 
 
    RectTransform _Panel;
    Rect LastRect = new Rect(0, 0, 0, 0);
 
    RectTransform Panel
    {
        get
        {
            if (_Panel == null)
                _Panel = GetComponent<RectTransform>();
            return _Panel;
        }
    }
 
    void Awake()
    {
        Refresh();
    }
 
    void Update()
    {
        Refresh();
    }
 
    void Refresh()
    {
        if (LastRect != Panel.rect)
            ApplySafeArea();
    }
 
    public void ApplySafeArea()
    {
        Panel.anchorMin = Vector2.zero;
        Panel.anchorMax = Vector2.one;
        //竖屏
        if (Screen.height > Screen.width)
        {
            if (Screen.height / Screen.width > 1.8)//宽屏需要适配
            {
                //上下各间隔SafeWidth
                Panel.offsetMin = new Vector2(0, SafeBottom);
                Panel.offsetMax = new Vector2(0, -SafeWidth);
            }
            else
            {
                Panel.offsetMin = new Vector2(0, 0);
                Panel.offsetMax = new Vector2(0, 0);
            }
        }
        else
        {//横屏
            if (Screen.width / Screen.height > 1.8)//宽屏需要适配
            {
                //两边各间隔SafeWidth
                Panel.offsetMin = new Vector2(SafeWidth, 0);
                Panel.offsetMax = new Vector2(-SafeWidth, 0);
            }
            else
            {
                Panel.offsetMin = new Vector2(0, 0);
                Panel.offsetMax = new Vector2(0, 0);
            }
        }
        LastRect = Panel.rect;
    }
    
}