如何判断两个CGRect是否相交?

时间:2021-06-12 11:30:39

In -drawRect: I want to check if the provided rect intersects with anotherRect.

In -drawRect:我想检查提供的rect是否与anotherRect相交。

I'm not good at this geometry math stuff and especially at english so what I want to say is:

我不擅长这种几何数学的东西,尤其是英语,所以我想说的是:

If you have two sheets of paper on the desk, and one of them covers the other either completely or just a small portion, it is rectsIntersect = YES.

如果桌面上有两张纸,其中一张纸完全覆盖另一张纸或只是一小部分纸,则rectsIntersect = YES。

How to check that out for rect and anotherRect?

如何检查rect和anotherRect?

2 个解决方案

#1


61  

Use bool CGRectIntersectsRect (CGRect rect1,CGRect rect2);

使用bool CGRectIntersectsRect(CGRect rect1,CGRect rect2);

Swift 3:

斯威夫特3:

public func intersects(_ rect2: CGRect) -> Bool

Example: rect1.intersects(rect2)

示例:rect1.intersects(rect2)

#2


1  

Try to use this.. While animating imageview you can get its actual frame by this:

尝试使用此..在动画imageview时,您可以通过以下方式获取其实际帧:

[[obstacle1.layer presentationLayer] frame];

So, it will easily to make collision of two imageview

因此,它很容易使两个imageview碰撞

if (CGRectIntersectsRect([[obstacle1.layer presentationLayer] frame], [[bgImageView.layer
    presentationLayer] frame])) 
{

    NSLog(@"Collision 1");

}

#1


61  

Use bool CGRectIntersectsRect (CGRect rect1,CGRect rect2);

使用bool CGRectIntersectsRect(CGRect rect1,CGRect rect2);

Swift 3:

斯威夫特3:

public func intersects(_ rect2: CGRect) -> Bool

Example: rect1.intersects(rect2)

示例:rect1.intersects(rect2)

#2


1  

Try to use this.. While animating imageview you can get its actual frame by this:

尝试使用此..在动画imageview时,您可以通过以下方式获取其实际帧:

[[obstacle1.layer presentationLayer] frame];

So, it will easily to make collision of two imageview

因此,它很容易使两个imageview碰撞

if (CGRectIntersectsRect([[obstacle1.layer presentationLayer] frame], [[bgImageView.layer
    presentationLayer] frame])) 
{

    NSLog(@"Collision 1");

}