[英]Get the Rect property of a UI object inside a Canvas that has the HorizontalLayoutGroup Component
[英]how to check UI rect inside Canvas rect
如何檢查 Canvas rect 內的 UI rect?
rect.contains(Vector2) 是 Vector2...
rect.overlaps(Rect) 不會為假,除非完全在外面...
void Update()
{
Vector2 pos;
var screenPos = Camera.main.WorldToScreenPoint(targetTransform.position + offset);
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRectTransform, screenPos, uiCamera, out pos);
if (!CheckInsideRect(myRectTransform.rect,canvasRectTransform.rect))
{
myRectTransform.localPosition = pos;
}
}
我想得到的結果
您可以通過使用一些擴展方法來“手動”完成它
public static class RectTransformExtensions
{
///<summary>
/// Returns a Rect in WorldSpace dimensions using <see cref="RectTransform.GetWorldCorners"/>
///</summary>
public static Rect GetWorldRect(this RectTransform rectTransform)
{
// This returns the world space positions of the corners in the order
// [0] bottom left,
// [1] top left
// [2] top right
// [3] bottom right
var corners = new Vector3[4];
rectTransform.GetWorldCorners(corners);
Vector2 min = corners[0];
Vector2 max = corners[2];
Vector2 size = max - min;
return new Rect(min, size);
}
///<summary>
/// Checks if a <see cref="RectTransform"/> fully encloses another one
///</summary>
public static bool FullyContains (this RectTransform rectTransform, RectTransform other)
{
var rect = rectTransform.GetWorldRect();
var otherRect = other.GetWorldRect();
// Now that we have the world space rects simply check
// if the other rect lies completely between min and max of this rect
return rect.xMin <= otherRect.xMin
&& rect.yMin <= otherRect.yMin
&& rect.xMax >= otherRect.xMax
&& rect.yMax >= otherRect.yMax;
}
}
請參見RectTransform.GetWorldCorners
所以你會像這樣使用它
if (!canvasRectTransform.FullyContains(myRectTransform))
{
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.