skip to Main Content

I currently need to calculate/ find the frame in an overlapped area of two UIViews. As an example, I have attached an image of two UIViews overlapping, as well as a white outline of the area/ frame that I would like to calculate – the output should be the frame of the overlapped area.
There is no code at the moment as the problem only requires two simple UIViews with slightly varied frames (to which they will to be compared).
Thanks in advance 😄

Updated image to include more examples of different cases:
different overlapping rectangle cases

2

Answers


  1. Chosen as BEST ANSWER

    I managed to find CGRectIntersection(_:_:) in Apple's documentation (https://developer.apple.com/documentation/coregraphics/1455346-cgrectintersection) and was able to discover that the frame of the overlapped area (of two intersecting frames) can be found using the following:

    let intersectionFrame: CGRect = view1.frame.intersection(view2.frame)
    

  2. For anyone interested, here’s the Mathematical version:

    func getIntersectionFrame(frame1: CGRect, frame2: CGRect) -> CGRect  {
        let x = frame1.isLeft(to: frame2) ? frame2.minX: frame1.minX
        let y = frame1.isHigher(than: frame2) ? frame2.minY: frame1.minY
        let width = abs(min(frame1.maxX, frame2.maxX)) - abs(x)
        let height = abs(min(frame1.maxY, frame2.maxY)) - abs(y)
        let intersectionRect = CGRect(x: x, y: y, width: width, height: height)
        return intersectionRect
    }
    
    extension CGRect {
        func isHigher(than rect: CGRect) -> Bool {
            return minY < rect.minY
        }
        func isLeft(to rect: CGRect) -> Bool {
            return minX < rect.minX
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search