美文网首页
convertRect

convertRect

作者: 何小八 | 来源:发表于2018-05-09 14:52 被阅读0次
    // 将像素point由point所在视图转换到目标视图view中,返回在目标视图view中的像素值
    - (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;
    
    // 将像素point从view中转换到当前视图中,返回在当前视图中的像素值
    - (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;
    
    // 将rect由rect所在视图转换到目标视图view中,返回在目标视图view中的rect
    - (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;
    
    // 将rect从view中转换到当前视图中,返回在当前视图中的rect
    - (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;
    
    

    例子:先创建view1和view2

        UIView *view1 = ({
           
            UIView *view = [[UIView alloc] init];
            view.frame = CGRectMake(20, 100, 300, 200);
            view.backgroundColor = [UIColor redColor];
            
            view;
            
        });
        
        UIView *view2 = ({
            
            UIView *view = [[UIView alloc] init];
            view.frame = CGRectMake(30, 110, 100, 100);
            view.backgroundColor = [UIColor blueColor];
            
            view;
            
        });
        //把view1加在self.view上,把view2加在view1上
        [self.view addSubview:view1];
        [view1 addSubview:view2];
    
    1.png

    convertRect

        //目标:算出view2在self.view上frame
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        CGRect view2Rect = view2.frame;
        NSLog(@"%@", NSStringFromCGRect(view2Rect));  //{{30, 110}, {100, 100}}
    
       //使用convertRect:toView
        //1. 使用view2的superview 来调用,那么要传的rect为view2.frame
        CGRect view2WinodwRect1 = [view2.superview convertRect:view2.frame toView:self.view];
        NSLog(@"%@", NSStringFromCGRect(view2WinodwRect1));//{{50, 210}, {100, 100}}
        
        //2. 使用view2自己来调用,那么要传的rect为view2.bounds;
        //如果传入view2.frame,系统则会多计算出view2在他的superview中的x和y,
        //最后结果就是 x = 2 * view2.superview.x + view2.x , y =  2 * view2.superview.y + view2.y
        CGRect view2WinodwRect2 = [view2 convertRect:view2.bounds toView:self.view];
        NSLog(@"%@", NSStringFromCGRect(view2WinodwRect2));//{{50, 210}, {100, 100}}
    
        //使用convertRect:fromView
        //3.
        CGRect view2WinodwRect3 = [self.view convertRect:view2.frame fromView:view2.superview];
        NSLog(@"%@", NSStringFromCGRect(view2WinodwRect3));//{{50, 210}, {100, 100}}
    
        //4.
        CGRect view2WinodwRect4 = [self.view convertRect:view2.bounds fromView:view2];
        NSLog(@"%@", NSStringFromCGRect(view2WinodwRect4));//{{50, 210}, {100, 100}}
    
      ### 注意点:
       toView: nil 和 fromView:nil  的参数为nil的时候默认是keyWindow,但是要注意keyWindow是否为null,
       当没有在AppDelegate中创建self.window的时候,获取[UIApplication sharedApplication].keyWindow的时候    
       可能为null。
    

    相关文章

      网友评论

          本文标题:convertRect

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