代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UILimit
{
public static bool UIAreaLimit(RectTransform target,Rect area,Transform root)
{
Bounds bounds = RectTransformUtility.CalculateRelativeRectTransformBounds(root, target);
Vector2 delta = default;
//左
if (bounds.center.x - bounds.extents.x < area.x)
{
delta.x += Mathf.Abs(bounds.center.x - bounds.extents.x - area.x);
}
//右
else if (bounds.center.x + bounds.extents.x > area.width / 2)
{
delta.x -= Mathf.Abs(bounds.center.x + bounds.extents.x - area.width / 2);
}
//上
if (bounds.center.y - bounds.extents.y < area.y)
{
delta.y += Mathf.Abs(bounds.center.y - bounds.extents.y - area.y);
}
//下
else if (bounds.center.y + bounds.extents.y > area.height / 2)
{
delta.y -= Mathf.Abs(bounds.center.y + bounds.extents.y - area.height / 2);
}
target.anchoredPosition +=delta;
return delta != default;
}
}
测试代码
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UILimitTest : MonoBehaviour
{
public RectTransform rt1;
private Rect rect;
CanvasScaler canvasScaler;
private void Awake()
{
canvasScaler = GetComponent<CanvasScaler>();
rect = new Rect(-Screen.width/4 , -Screen.height/4 , Screen.width/2, Screen.height/2);
}
private void Update()
{
UILimit.UIAreaLimit(rt1, rect, transform);
}
}