Arcadian
Arcadian

Reputation: 4350

iphone: CGRectInterest, hit test

I have a UIImageView inside a UIScrollView, I have another UIImageView (dragImage) that is outsite the scrollview but inside a main View Controller's view with the UIScrollVIew.

I want to check to see if the dragImage intersects with the imageview inside the scrollview and also want to know how much is intersects..

What is a good method?

This is my result/code and it works pretty good:

CGRect tabFrame = CGRectMake(0, ((TAB_HEIGHT+2)*i) + scrollView.frame.origin.y, TAB_WIDTH, TAB_HEIGHT);
            CGRect dragFrame = dragImage.frame;

            CGRect collision = CGRectIntersection(dragFrame,tabFrame);

            int area = collision.size.width * collision.size.height;

            if (area>selectedArea) {
                selectedArea = area;
                selectedTab=i;
            }


            if (selectedArea>600) break;

Upvotes: 1

Views: 1049

Answers (2)

Mark Adams
Mark Adams

Reputation: 30846

You'll want to use CGRectIntersectsRect() and CGRectIntersection() to derive if two rectangles overlap and by how much, respectively. For instance...

BOOL dragImageIntersectsScrollView = CGRectIntersectsRect(dragImage.frame, scrollView.frame);
CGRect intersectionRect = CGRectIntersection(dragImage.frame, scrollView.frame);

if (!dragImageIntersectsScrollView)
{
    NSLog(@"Rectangles do not intersect");
}
else
{
    NSLog(@"Intersection rect: %@", NSStringFromCGRect(intersectionRect))
}

CGRectIntersectsRect() isn't absolutely essential because you could just check the return value of CGRectIntersection(). If they don't intersect then it will return a null rectangle. You can check for this with CGRectIsNull().

Upvotes: 2

Tony
Tony

Reputation: 4609

UIImageView inside the UIScrollView = A, and drag view = B and UIScrollView = scroll. Take the offset of A.y in the scroll + scroll.y = j.y to get the y position of the UIImageView and then take the offset of A.x in the scroll + scroll.x = j.x, this will get you the xy position of the imageview and you can easily access the width of the UIImageView. Assuming you have a variable that is assigned to A. THen you simply take the x of B and the x of A and see if B.x > j.x && b.x < j.x + a.width to check to see if the top left x position is somewhere in the box and b.y > j.y && b.y < j.y + a.width. Basically you can do whatever math you want after you have gotten the offset from the scroll view and the scrollviews position to get the actual x and y of the UIImageView.

Upvotes: -1

Related Questions