tags:

views:

15

answers:

1

I am working on a drawing program and am trying to figure out the best way to imitate the 'magnet' behavior found in applications such as Omnigraffle. The idea is: as a line is drawn between two objects (visual objects on screen, not OOP objects), as the line from the first object approaches the second, a 'magnet' or 'node' on the second will highlight or the second object will highlight.

I was looking to keep all of the on-screen objects in an array and using notifications to send that array the position of the end of the line as it moves. This way, I could have each object do its own comparison and say "Hey, I have a node near the line, I think I'll light it up".

I was also wondering if it would be the same approach if I wanted to have two objects, say boxes for instance, that would snap together, side by side, when they came into proximity with each other. This way, it would be possible to line up the boxes on the same X or Y coordinate

I'm not concerned about the highlighting or having the line snap to the position of a node, I'm just wondering about the best way to implement the 'edge proximity detection' part of this problem.

A: 

If you are using CGRect types I'd suggest you use the two functions CGRectInset() and CGRectIntersectsRect()

Use CGRectInset() to expand one or both rects and then use CGRectIntersectsRect() to see if you have a match. You could also use (at the same time) CGRectIntersectsRect() on the original rects to see that you only have are close and not covering each other.

epatel
If I understand you correctly, I would take the CGRect from each object in the array, create a larger CGRect using CGRectInset() then call CGRectIntersectsRect() on each new CGRect and those that return YES, have perform some action. So my thinking on using the array to contain the objects is the most efficient method?
noizetoys
@noizetoys Yes, more or less. If you are only moving one object you could take it's rect and make that larger with CGRectInset, then test that rect agains every other objects rect.
epatel