[英]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.Min
和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軸在世界上對齊(這是您最初的嘗試)。
使用RectTransform.GetWorldCorners獲取圖像的所有角。
找到最小和最大點。
使用Bounds.SetMinMax來獲取邊界。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.