判断UI元素超出屏幕

这里只判断UI元素的RectTransform,不判断实际UI元素实际绘制区域,代码如下

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
local halfW = 121
local halfH = 50
function GuideDesPosView:CalcUiBound()
if not self.m_desPos then
return
end

local value = Camera.main:WorldToScreenPoint(self.m_desPos)
local x = value.x
local y = value.y
local z = value.z
if x == self.m_lastX and y == self.m_lastY and z == self.m_lastZ then
return
end

if z < 0 then
if self.contentTrans.gameObject.activeSelf then
self.contentTrans.gameObject:SetActive(false)
end
return
elseif z >= 0 then
if self.m_lastZ >= 0 then
self.contentTrans.gameObject:SetActive(true)
end
end

local scaleX = 1920 / Screen.width
local scaleY = 1080 / Screen.height

self.m_lastX = x
self.m_lastY = y
self.m_lastZ = z
if (value.x + halfW > Screen.width) then
x = Screen.width - halfW
end

if (value.x - halfW < 0) then
x = halfW
end

if (value.y - halfH < 0) then
y = halfH
end

if (value.y + halfH > Screen.height) then
y = Screen.height - halfH
end

self.contentRectTrans.localPosition = Vector3((x - Screen.width / 2) * scaleX, (y - Screen.height / 2) * scaleY, 0)
end