在iOS中重叠和交换图像

时间:2014-04-24 13:01:26

标签: ios objective-c

我想交换两张图片。当我移动拖动图像并且它在视图中的任何其他图像上重叠 50%或更高时,必须交换它。问题是如何检查拖动图像与其他图像重叠50%或50%以上。请通过代码示例帮助并建议逻辑。

我正在尝试的代码是:

if (imgVw.tag != self.tag) { 
     CGRect imgVwRect = CGRectMake(imgVw.frame.origin.x +(imgVw.frame.size.width/2), imgVw.frame.origin.y+(imgVw.frame.size.height/2), imgVw.frame.size.width, imgVw.frame.size.height);

     CGRect movingImgRect = CGRectMake(newCenter.x+self.frame.size.width, newCenter.y+self.frame.size.height, self.frame.size.width, self.frame.size.height);

    if (movingImgRect.origin.x >= imgVwRect.origin.x && movingImgRect.origin.y >= imgVwRect.origin.y)
    {

         NSLog(@"img view tag %lu",imgVw.tag);
         UIImage *tempImg = self.image;
         [self setImage:imgVw.image];
         [imgVw setImage:tempImg];                  
     }

}

1 个答案:

答案 0 :(得分:0)

这非常简单。

使用方法CGRectIntersection计算2个rects的交集。

然后将交叉区域与移动矩形区域进行比较。这样的事情(假设我理解你的代码

if (imgVw.tag != self.tag) 
{ 
  CGRect imgVwRect = CGRectMake(imgVw.frame.origin.x +(imgVw.frame.size.width/2),
    imgVw.frame.origin.y+(imgVw.frame.size.height/2), 
    imgVw.frame.size.width, 
    imgVw.frame.size.height);

  CGRect movingImgRect = CGRectMake(newCenter.x+self.frame.size.width,
    newCenter.y+self.frame.size.height, 
    self.frame.size.width, 
    self.frame.size.height);

  //Figure out the intersection rect of the 2 rectangles
  CGRect intersectionRect = CGRectIntersection(imgVwRect, movingImgRect);

  //Find the area of the intersection
  CGFloat xArea = intersectionRect.size.height * intersectionRect.size.width;

  //Find the area of the moving image 
  //(this code could be done once and saved in an iVar)
  CGFloat movingImgArea = movingImgRect.size.height * movingImgRect.size.width;

  //Is the intersection >= 1/2 the size of the moving image?
  if (xArea*2 >= movingImgArea)
  {
    //Do whatever you need to do when the 2 images overlap by >= 50%
  }
}