Intersection Of Two UIViewImages

How can I determine if two uiviewimages intersect. I want to do an auto snap feature. When the small image intersects with the big image or close to it (Lets says the distance<=x), I want the small image automatically snap(connect) to the big image at the point where they intersect.

Upvotes: 3

Views: 2428

Answers (3)

pasawaya
pasawaya

Reputation: 11595

The previous two posters have been on the right track with CGRectIntersectsRect.

BOOL isIntersecting = CGRectIntersectsRect(smallImage.frame, largeImage.frame);
if(isIntersecting){

    //Animate the Auto-Snap
    [UIView beginAnimation:@"animation" context:nil];
    [UIView setAnimationDuration:0.5];
    smallImage.frame = largeImage.frame;
    [UIView commitAnimations];
}

Basically what this says that if the two images are intersecting, the small image frame snap to the larger image over 0.5 seconds. You don't have to animate it though; you could just make it instantaneous by removing all code except for smallImage.frame = largeImage.frame;. However, I recommend the animation way. Hope this helps.

-------EDIT--------

You could use the code:

 BOOL isIntersecting = CGRectIntersectsRect(smallImage.frame, largeImage.frame);
 if(isIntersecting){     
     //Animation
     [UIView beginAnimation:@"animation" context:nil];
     [UIView setAnimationDuration:0.5];

     smallImage.center = CGPointMake(largeImage.center.x, largeImage.center.y);

     //If you want to make it like a branch, you'll have to rotate the small image
     smallImage.transform = CGAffineTransformMakeRotation(30);
     //The 30 is the number of degrees to rotate. You can change that.

     [UIView commitAnimations];
 }

Hope this fixed your problem. Remember to up vote and pick as the answer if this helped.

-------EDIT--------- One last thing. I said that the "30" in CGAffineTransformMakeRotation(30) stood for 30 degrees, but that is incorrect. The CGAffineTransformMakeRotation function takes its parameter in radians, so if you wanted 30 degrees you could do this:

#define PI 3.14159265

CGAffineTransformMakeRotation(PI/6);

Upvotes: 1

Chris Heyes
Chris Heyes

Reputation: 366

CGRect bigframe = CGRectInset(bigView.frame, -padding.x, -padding.y);

BOOL isIntersecting = CGRectIntersectsRect(smallView.frame, bigFrame);

Upvotes: 2

user523234
user523234

Reputation: 14834

You can use the CGRectIntersectsRect method to check for frames:

 if (CGRectIntersectsRect(myImageView1.frame, myImageView2.frame))
    {
        NSLog(@"intersected")
    }

Upvotes: 1

Related Questions