iOS坐标系的转换

测试过程中遇到的问题:

测试时是在ViewDidLoad方法中转换坐标系的,

    CGRect newRect = [self.redView convertRect:self.redView.bounds toView:nil];

使用这句代码时,转换出来的坐标系是错误的,原因是toView设置为nil,  convertRect方法会以keyWindow作为坐标系,在ViewDidLoad方法调用时,keyWindow是没有frame的,导致转换的坐标系是错误的;

 

 

08102232_poOp.png

test1.png

什么是坐标系的转换?

不同坐标系,控件的View的frame值是不同的,比如上图的红色View,以蓝色控件为父控件作为坐标系原点,那么它的frame的x = 50,y = 50;如果红色View以控制器的View为坐标系的原点,那么它的frame的x = 100 + 50,y = 100 + 50;
如果两个View进行比较,比如是否包含,是否交叉重叠,那么应该转换成同一坐标系,这样才可以直接比较;

1.同一坐标系View1和View2之间比较

  • 比如都是以控制器的View为父控件,以控制器的View的坐标原点作为参照点
    // rect1是否包含rect2,必须是同一个坐标系,返回值是bool
     CGRectContainsRect(rect1, rect2)
    // 是否有交叉,必须是同一个坐标系,返回值是bool
     CGRectIntersectsRect(rect1, rect2)
    // 这个点是否在这个矩形框内,返回值是bool
     CGRectContainsPoint(rect1, point)
  • 注意:同一坐标系两个View之间比较,rect是控件的frame,不是它的bound

2.不同坐标系View1和View2之间比较

首先了解两个重要的方法:

view2坐标系 : 以view2的左上角为坐标原点
view1坐标系 : 以view1的左上角为坐标原点

// 显然这里rect不是View的frame,而是bound 
// 让rect这个矩形框, 从view2坐标系转换到view1坐标系, 得出一个新的矩形框newRect
// rect和view2的含义 : 用来确定矩形框原来在哪
CGRect newRect = [view1 convertRect:rect fromView:view2];

// 让rect这个矩形框, 从view1坐标系转换到view2坐标系, 得出一个新的矩形框newRect
// rect和view1的含义 :用来确定矩形框原来在哪
CGRect newRect = [view1 convertRect:rect toView:view2];

1.确定redView在window中的位置和尺寸

// 这里用`CGRect newRect = [view1 convertRect:rect toView:view2];;
`,这个方法演示

// 方法一:
CGRect newRect = [self.redView convertRect:self.redView.bounds toView:[UIApplication sharedApplication].keyWindow];

// 方法二:
CGRect newRect = [self.redView.superview convertRect:self.redView.frame toView:[UIApplication sharedApplication].keyWindow];

// 方法三:
// 在这里 [UIApplication sharedApplication].keyWindow == nil;
CGRect newRect = [self.redView convertRect:self.redView.bounds toView:nil];

2.确定blueView在window中的位置和尺寸

// 这里用`CGRect newRect2 = [view1 convertRect:rect fromView:view2];
`,这个方法演示

// 注意这里` [[UIApplication sharedApplication].keyWindow`不能写nil
CGRect newRect = [[UIApplication sharedApplication].keyWindow convertRect:self.blueView.bounds fromView:self.blueView];

3.判断两个rect是否有交叉重叠

NSLog(@"%zd", CGRectIntersectsRect(newRect, newRect2));

3.1判断newRect是否包含newRect2

NSLog(@"%zd", CGRectContainsRect(newRect, newRect2));

3.封装代码,判断两个View是否有重叠

- (BOOL)intersectWithView:(UIView *)view
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    CGRect selfRect = [self convertRect:self.bounds toView:window];
    CGRect viewRect = [view convertRect:view.bounds toView:window];
    return CGRectIntersectsRect(selfRect, viewRect);
}

转载于:https://my.oschina.net/mexiaobai1315/blog/833804

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值