2011-12-19 96 views
0

我有2 UIImageViews其大小为50x50和60x60像素。UIImageView和CGRectIntersectRect(Xcode)

我使用CGRectIntersectRect方法来确定一个图像何时接触另一个图像。但是这2张图片是2个球,有时候代码会确定这些图片在你看到他们不接触的“你的眼睛”时会触及自己。发生这种情况是因为球不会“覆盖”图像的所有空间。所以图像的角落很清晰,但是代码并不关心这一点。

问题是:我该如何解决?我怎样才能确定完美的球周围的图像帧?

回答

2

如果你确信在UIImageView S上的图像将永远是圆(或UIImageView旨意永远是正方形),那么你可以这样做

CGRect frame1 = image1.frame; 
CGRect frame2 = image2.frame; 
CGPoint center1 = CGPointMake(CGRectGetMidX(frame1), CGRectGetMidY(frame1)); 
CGPoint center2 = CGPointMake(CGRectGetMidX(frame2), CGRectGetMidY(frame2)); 

CGFloat dx = center1.x - center2.x; 
CGFloat dy = center2.x - center2.y; 
float squaredDistance = dx * dx + dy * dy; 

CGFloat radius1 = frame1.size.width/2; 
CGFloat radius2 = frame2.size.width/2; 
CGFloat minDistance = radius1 + radius2; 
if (squaredDistance <= minDistance * minDistance) { 
    //Intersect 
} else { 
    //Do not intersect 
} 

我试图让一切参数,但当然,如果UIImageView的帧是固定的,那么您可以使用例如#define指令编写更简单的代码。

例如,如果你知道第一个图像是50×50,第二个是60×60,你可以写类似

#define RADIUS1 25 
#define RADIUS2 30 

和简化代码。

我假设每个圆都刻在UIImageView的框中。如果不是,那么你应该知道准确的比例来正确测量半径。 (到目前为止,更容易在框中刻上圆圈。)