如何在canvas中获取多个UI图像的组合边界?
How to get the combined bounds of multiple UI image in a canvas?
我正在尝试获取 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获取图像的所有角。
求最小点和最大点。
使用Bounds.SetMinMax获取边界。
您可以使用 RectTransform.GetWorldCorners
来获取每个图像的 4 个角的字坐标。
然后你可以迭代它们并使用Vector3.Min
and Vector3.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 轴世界对齐(正如您最初的尝试)。
我正在尝试获取 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获取图像的所有角。
求最小点和最大点。
使用Bounds.SetMinMax获取边界。
您可以使用 RectTransform.GetWorldCorners
来获取每个图像的 4 个角的字坐标。
然后你可以迭代它们并使用Vector3.Min
and Vector3.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 轴世界对齐(正如您最初的尝试)。