1

I am using CGRectIntersectsRect to test if blueView (being dragged) has intersected with redView (stationary). However, I need to know if redView was intersected by blueView from red's top, bottom, right or left? Is there a CG method to accomplish this?

Cesare
  • 9,139
  • 16
  • 78
  • 130
Kashif
  • 4,642
  • 7
  • 44
  • 97
  • I don't think there is a direct way to do this. You have to write all the complex conditions by comparing the corner points. And you also can enter through corners not just the sides. `CGRectIntersection` returns the intersection of the two rectangles. – rakeshbs Feb 19 '15 at 14:46

2 Answers2

0

I'm not aware of any CG Method to accomplish this.

The way I'd go about this is using CGRectIntersectsRect to check if they intersect at all, then if they do intersect, measure from the center of redView to blueView which would return the distance between them (X and Y), from that you could possibly tell from which angle the intersection was coming from?

If you wanted a little more accuracy you could measure from redView top center, to blueView bottom center, and the same for all 4 edges? Then work out which is the closest?

There are multiple ways you could approach this problem but I'm not aware of a 'one method fits all' solution.

Edit:

Was still thinking about this, I think the most accurate way would be something like this:

let leftDistance = blue.origin.x - (red.origin.x + red.width)
let rightDistance = (blue.origin.x + blue.width) - red.origin.x
let topDistance = blue.origin.y - (red.origin.y + red.height)
let bottomDistance = (blue.origin.y + blue.height) - red.origin.y

The the lowest of those distance = coming from the left, right, top or bottom.

(P.s. I might have gotten blue + Red the wrong way around, as well as top and bottom. I'd recommend just having a play around and logging these values while dragging the item)

Dave Leverton
  • 614
  • 3
  • 16
0

Here is the solution I finally used, In case someone else is looking for it. Below line of code test if the intersection is vertical (top & bottom views intersected), where a and b are view.frame for each of the two view intersecting.

if ((a.maxY > q.maxY) && (b.minY < q.minY)) || ((a.maxY < q.maxY) && (b.minY > q.minY))

Kashif
  • 4,642
  • 7
  • 44
  • 97