surendher raja
surendher raja

Reputation: 203

How to check whether two image views are in same position?

I am working in a project where the images are drag able. In which if i put one image over the other image the image has to be changed. What i need is 1) I want to check whether both the images are in same place or not. 2) The position of image must not be exact.It may be approximately equal

Upvotes: 2

Views: 604

Answers (4)

Antonio MG
Antonio MG

Reputation: 20410

If you want to check if two UIImages intersect, this is a good way:

CGRect rect1 = myView1.frame;
CGrect rect2 = myView2.frame;

if (CGRectIsNull(CGRectIntersection(rect1, rect2))) {
    //They collide
}

You have all the info you need about this here:

https://developer.apple.com/library/mac/#documentation/graphicsimaging/reference/CGGeometry/Reference/reference.html

Upvotes: 8

Jesse Black
Jesse Black

Reputation: 7986

Here is an approach assuming the images are the same size

// using ints because it is easier for taking the abs value
int dx,dy;

dx = frame1.origin.x - frame2.origin.x;
dy = frame1.origin.y - frame2.origin.y;
dx = abs(dx);
dy = abs(dy);

// overlapping width and height
int ovHeight, ovWidth;

ovWidth = frame1.size.width-dx;
ovHeight = frame1.size.height-dy;

int ovArea = ovWidth*ovHeight;
int imageArea = frame1.width*frame1.height;

int percentOverlap = ovArea*100/imageArea;

if (percentOverlap > 80) {
  // do work here
}

Upvotes: 2

mayuur
mayuur

Reputation: 4746

//for checking whether one image is inside another image
if(CGRectContainsRect(ImageView1.frame, ImageView2.frame))
{
    //your code for overlapping here
}

//for checking whether one image intersects another
if(CGRectIntersectsRect(ImageView1.frame,ImageView2.frame))
{
    //your code for intersection here        
}

Upvotes: 4

Shubhank
Shubhank

Reputation: 21805

CGRect frame1 = imgView1.frame;
CGRect frame2 = imgView2.frame;

this will give you two frame structures..which consist of origin(x,y) values and size(width,height) values..

compare according to your needs.

Upvotes: 1

Related Questions