Reputation: 687
I'm trying to want to write an method whenever two UIImageViews intersect. The only way I know how to do it is CGRectIntersectsRect. But that only works with rectangles, but my images are circles. Isn't there a better alternative? Thank you!
Upvotes: 2
Views: 1658
Reputation: 725
You can do something like this:
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.
}
Upvotes: 5
Reputation: 75
It's use core animation.
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];
Upvotes: 1
Reputation: 13713
Assuming you know the radius of each circle (if the image is a square in size then it will be height/2
or width/2
if the circle entirely occupies fills the image) do the following for detecting collision between two circles:
Calculate the distance between the center point of the two circle:
distance = sqrt((p1.x - p2.x)^2 + (p1.y - p2.y)^2)
;
p1 - Center point of circle 1
p2 - Center point of circle 2
Calculate the sum of the radius of the two circles :
radiusSum = radius1 + radius2;
If distance <= radiusSum
then you have a collision
Upvotes: 1