我想在两个UIImageViews相交时想要编写一个方法。我知道如何做的唯一方法是CGRectIntersectsRect。但这仅适用于矩形,但我的图像是圆形。难道没有更好的选择吗?谢谢!
答案 0 :(得分:5)
您可以这样做:
CGPoint a = imageViewA.center;
CGPoint b = imageViewB.center;
CGFloat distance = sqrt(pow((b.x - a.x),2) + pow((b.y - a.y),2));
if(distance < (imageViewA.bounds.size.width/2.0 + imageViewB.bounds.size.width/2.0)){
//images are touching.
}
答案 1 :(得分:1)
假设你知道每个圆的半径(如果图像是一个正方形的大小,那么它将是height/2
或width/2
如果圆完全占据填充图像)执行以下操作来检测碰撞在两个圈子之间:
计算两个圆的中心点之间的距离:
distance = sqrt((p1.x - p2.x)^2 + (p1.y - p2.y)^2)
;
p1 - Center point of circle 1
p2 - Center point of circle 2
计算两个圆的半径之和:
radiusSum = radius1 + radius2;
如果distance <= radiusSum
则发生碰撞
答案 2 :(得分:1)
它使用核心动画。
CALayer *subLayer = [CALayer layer];
subLayer.backgroundColor = [UIColor blueColor].CGColor;
subLayer.shadowOffset = CGSizeMake(0, 3);
subLayer.shadowRadius = 100.0;
subLayer.shadowColor = [UIColor blackColor].CGColor;
subLayer.shadowOpacity = 0.8;
subLayer.frame = CGRectMake(30, 30, 128, 192);
subLayer.borderColor = [UIColor blackColor].CGColor;
subLayer.borderWidth = 2.0;
subLayer.cornerRadius = 10.0;
[self.view.layer addSublayer:subLayer];
CALayer *imageLayer = [CALayer layer];
imageLayer.frame = subLayer.bounds;
imageLayer.cornerRadius = 48.0;// Here set you right size, then they looks like a circles
imageLayer.contents = (id)[UIImage imageNamed:@"141.png"].CGImage;
imageLayer.masksToBounds = YES;
[subLayer addSublayer:imageLayer];