Objective-C 判断两个矩形是否相交

本文介绍了一种用于判断两个矩形是否相交的算法,并提供了具体的实现代码。该算法通过比较矩形的边界坐标来确定它们是否发生重叠。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题定义:定义一个矩形类,实现判断矩形是否相交的方法。

思路:给定两个边与坐标轴平行的矩形,分别由左上角与右下角两点指定,即矩形(P1,P2)与(P3,P4),判断两矩形是否相交。如下图所示,首先求出P1与P3点在X方向较大值与Y方向较大值的交点,在下图中就是P3,用红点(记为M点)表示。然后求出P2与P4点在X方向较小值与Y方向较小值的交点,在下图中就是P2,用橙色点(记为N点)表示。如果M点的X坐标和Y坐标值均比N点相应的X坐标和Y坐标值小,亦即M和N可以分别构成一个矩形的左上角点和右上角点,则两矩形相交;其余情况则不相交。

01165312-e31340b5153448d2a02a10dd82de62d2.png01170805-2e6a26fef97c4e1ca7104664a2e5c589.png01171401-cde500e2eefc4319a3c63c484d820f62.png

WFRect

#import <Foundation/Foundation.h>


@interface WFRect : WFShape


@property (nonatomic,assigndouble width;

@property (nonatomic,assigndouble height;



+ (instancetype) rectWithX : (double) x

                         y : (double) y

                      width: (double) width

                     height: (double) height;


- (instancetype)initWithX : (double) x

                        y : (double) y

                     width: (double) width

                    height: (double) height;

@end



WFRect.m

#import "WFRect.h"


@implementation WFRect


+(instancetype)rectWithX:(double)x

                       y:(double)y

                  width:(double)width

                  height:(double)height{

    return [[self allocinitWithX:x y:y width:width height:height];

}


- (instancetype)initWithX:(double)x

                        y:(double)y

                   width:(double)width

                    height:(double)height{

    if (self = [super init]) {

_x = x;

_y = y;

        _width = width;

        _height = height;

    }

    return self;

}


-(BOOL) intersects:(WFRect *) other{

    double redX = _x > other.x ? _x : other.x;

    double redY = _y > other.y ? _y : other.y;

    double yellowX = _x + _width < other.x + other.width ?_x + _width : other.x + other.width;

    double yellowY = _y + _height < other.y + other.height ? _y +_height : other.y + other.height;

    return (yellowX > redX && yellowY > redY);

}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值