繁体   English   中英

如何获取画布中多个UI图像的组合范围?

[英]How to get the combined bounds of multiple UI image in a canvas?

我正在尝试在画布中获取多个ui图像的边界。 我正在使用此代码:

Bounds bounds = new Bounds(imageList[0].transform.position, Vector3.zero);
for (int i = 0; i < imageList.Count; i++)
{
    bounds.Encapsulate(imageList[i].transform.position);
}

但是,如果我有两个图像,则边界将在每个图像的中间开始和结束。 使用游戏对象立方体,球体等时,此代码有效,但使用UI时,结果不同。

您可以使用RectTransform.GetWorldCorners来获取每个Image在单词坐标中的4个角。

然后,您可以遍历它们,并使用Vector3.MinVector3.Max计算所有图像的所有角的最小值和最大值。

最后使用Bounds.SetMinMax来使用此最小值和最大值创建一个边界框。

public class Example : MonoBehaviour
{
    public List<Image> imageList = new List<Image>();

    private void OnDrawGizmos()
    {
        var min = Vector3.positiveInfinity;
        var max = Vector3.negativeInfinity;

        foreach (var image in imageList)
        {
            if(!image) continue;

            // Get the 4 corners in world coordinates
            var v = new Vector3[4];
            image.rectTransform.GetWorldCorners(v);

            // update min and max
            foreach (var vector3 in v)
            {
                min = Vector3.Min(min, vector3);
                max = Vector3.Max(max, vector3);
            }
        }

        // create the bounds
        var bounds = new Bounds();
        bounds.SetMinMax(min, max);

        Gizmos.color = Color.red;
        Gizmos.DrawWireCube(bounds.center, bounds.size);
    }
}

注意:此边界框将与全局XYZ轴在世界上对齐(这是您最初的尝试)。


在此处输入图片说明

  1. 使用RectTransform.GetWorldCorners获取图像的所有角。

  2. 找到最小和最大点。

  3. 使用Bounds.SetMinMax来获取边界。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM