美文网首页
iOS 坐标转换

iOS 坐标转换

作者: 愁云 | 来源:发表于2017-12-14 13:41 被阅读12次

    首先添加一个redView和一个greenView,其中greenView是添加到redView上面。

    UIView * redView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, 300, 300)]; 

    redView.backgroundColor = [UIColor redColor];

     [self.view addSubview:redView]; UIView * greenView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)]; 

    greenView.backgroundColor = [UIColor greenColor]; 

    [redView addSubview:greenView]; 

    NSLog(@"----redView在self.view的中frame:%@",NSStringFromCGRect(redView.frame)); 

    NSLog(@"----greenView在redView的中frame:%@",NSStringFromCGRect(greenView.frame)); 

    现在要将greenView在redView的frame ---> self.view 转换计算,方法有以下两种:

    方法1  调用- (CGRect)convertRect:(CGRect)rect toView:(nullable UIView *)view; convertRect:待转换的view的frame 或者bounds toView:目标坐标系参考view,如果传nil,就是以当前window为参考系 调用者:原rect所在坐标系统的直接关联view 这里greenView.frame 原来是参照父控件(superview)redView计算坐标的 如果传入的是greenView.bounds,那么是参考其自身计算坐标的,调用者就是greenView 

    CGRect RectInView1= [redView convertRect:greenView.frame toView:self.view];

    CGRect RectInView2= [greenView convertRect:greenView.bounds toView:self.view]; 

    CGRect RectInView3= [greenView.superview convertRect:greenView.frame toView:self.view]; 

    NSLog(@"将greenView在self.view的frame ---> self.view :%@",NSStringFromCGRect(RectInView1)); 

    NSLog(@"将greenView在self.view的frame2 ---> self.view :%@",NSStringFromCGRect(RectInView2));

     NSLog(@"将greenView在self.view的frame3 ---> self.view :%@",NSStringFromCGRect(RectInView3)); 

    方法2 调用 - (CGRect)convertRect:(CGRect)rect fromView:(nullable UIView *)view;

    CGRect RectFromView1 = [self.view convertRect:greenView.frame fromView:redView]; 

    CGRect RectFromView2 = [self.view convertRect:greenView.bounds fromView:greenView]; 

    CGRect RectFromView3 = [self.view convertRect:greenView.frame fromView:greenView.superview];

     NSLog(@"将greenView在self.view的frame3 ---> self.view :%@",NSStringFromCGRect(RectFromView1)); 

    NSLog(@"将greenView在self.view的frame4 ---> self.view :%@",NSStringFromCGRect(RectFromView2));

    打印结果:


    相关文章

      网友评论

          本文标题:iOS 坐标转换

          本文链接:https://www.haomeiwen.com/subject/awckwxtx.html