简体   繁体   中英

how to check UI rect inside Canvas rect

How to check UI rect inside Canvas rect?

rect.contains(Vector2) is Vector2...

rect.overlaps(Rect) Will not be false unless it is completely outside...

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;
    }
}

The results I would like to get

我要1 我要2

You could do it "manually" by using some extension methods something like

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;
    }
}

See RectTransform.GetWorldCorners

So you would use it like

if (!canvasRectTransform.FullyContains(myRectTransform))
{
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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