Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS CGRect is inside another CGRect

Tags:

ios

uiview

cgrect

Anyone has a good solution for the following task?

I need to check if a CGRect is inside another CGRect and return a CGPoint, that gives the offset if the rect window is outside in any dimension from the containing.

thanks in advance

like image 380
Bence Pattogato Avatar asked Jun 08 '15 15:06

Bence Pattogato


2 Answers

Swift 4.1

// Returns how much is the rect outside of the view, 0 if inside
func isRectVisibleInView(rect: CGRect, inRect: CGRect) -> CGPoint {
    var offset = CGPoint()

    if inRect.contains(rect) {
        return CGPoint(x: 0, y: 0)
    }

    if rect.origin.x < inRect.origin.x {
        // It's out to the left
        offset.x = inRect.origin.x - rect.origin.x
    } else if (rect.origin.x + rect.width) > (inRect.origin.x + inRect.width) {
        // It's out to the right
        offset.x = (rect.origin.x + rect.width) - (inRect.origin.x + inRect.width)
    }

    if rect.origin.y < inRect.origin.y {
        // It's out to the top
        offset.y = inRect.origin.y - rect.origin.y
    } else if rect.origin.y + rect.height > inRect.origin.y + inRect.height {
        // It's out to the bottom
        offset.y = (rect.origin.y + rect.height) - inRect.origin.y + inRect.height
    }


    return offset
}

Swift 3 update

// Returns how much is the rect outside of the view, 0 if inside
func isRectVisibleInView(rect: CGRect, inRect: CGRect) -> CGPoint {
    var offset = CGPoint()

    if CGRectContainsRect(inRect, rect) {
        return CGPointMake(0, 0)
    }

    if rect.origin.x < inRect.origin.x {
        // It's out to the left
        offset.x = inRect.origin.x - rect.origin.x
    } else if (rect.origin.x + rect.width) > (inRect.origin.x + inRect.width) {
        // It's out to the right
        offset.x = (rect.origin.x + rect.width) - (inRect.origin.x + inRect.width)
    }

    if rect.origin.y < inRect.origin.y {
        // It's out to the top
        offset.y = inRect.origin.y - rect.origin.y
    } else if rect.origin.y + rect.height > inRect.origin.y + inRect.height {
        // It's out to the bottom
        offset.y = (rect.origin.y + rect.height) - inRect.origin.y + inRect.height
    }


    return offset
}
like image 85
Bence Pattogato Avatar answered Oct 12 '22 22:10

Bence Pattogato


Maybe

CGRectContainsRect(CGRect rect1, CGRect rect2)

to check if cgrect is inside another, this method return a bool.

like image 45
Nekak Kinich Avatar answered Oct 12 '22 22:10

Nekak Kinich