美文网首页
iOS-convertRect和convertPoint用法

iOS-convertRect和convertPoint用法

作者: Imkata | 来源:发表于2022-03-08 01:18 被阅读0次

下面代码看懂就理解它们两个的用法了。

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    //red父view
    UIView *red = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
    red.backgroundColor = [UIColor redColor];
    [self.view addSubview:red];
    
    //blue子view
    UIView *blue = [[UIView alloc] initWithFrame:CGRectMake(100 ,100 ,50 ,50)];
    blue.backgroundColor = [UIColor blueColor];
    [red addSubview:blue];
    
    //打印:{{200, 200}, {50, 50}}
    //blue.frame就是(100 ,100 ,50 ,50),把相对于red的这个矩形框,转成相对于self.view的矩形框,所以是{{200, 200}, {50, 50}}
    CGRect newRec = [red convertRect:blue.frame toView:self.view];
    //打印:{{100, 100}, {50, 50}}
    //blue.bounds就是(0 ,0 ,50 ,50),把相对于red的这个矩形框,转成相对于self.view的矩形框,所以是{{100, 100}, {50, 50}}
    CGRect newRec2 = [red convertRect:blue.bounds toView:self.view];
    //打印:{{300, 300}, {50, 50}}
    //blue.frame就是(100 ,100 ,50 ,50),把相对于blue的这个矩形框,转成相对于self.view的矩形框,所以是{{300, 300}, {50, 50}}
    CGRect newRec3 = [blue convertRect:blue.frame toView:self.view];
    //打印:{{200, 200}, {50, 50}}
    //blue.bounds就是(0 ,0 ,50 ,50),把相对于blue的这个矩形框,转成相对于self.view的矩形框,所以是{{200, 200}, {50, 50}}
    CGRect newRec4 = [blue convertRect:blue.bounds toView:self.view];
    NSLog(@"%@-%@-%@-%@",NSStringFromCGRect(newRec),NSStringFromCGRect(newRec2),NSStringFromCGRect(newRec3),NSStringFromCGRect(newRec4));
    
    //打印:{225, 225}
    //blue.center就是{125, 125},把相对于red的这个点,转成相对于self.view的点,所以是{225, 225}
    CGPoint newPoint = [red convertPoint:blue.center toView:self.view];
    //打印:{325, 325}
    //blue.center就是{125, 125},把相对于blue的这个点,转成相对于self.view的点,所以是{325, 325}
    CGPoint newPoint2 = [blue convertPoint:blue.center toView:self.view];
    NSLog(@"%@-%@",NSStringFromCGPoint(newPoint),NSStringFromCGPoint(newPoint2));
}

平常我们使用最多的是:

CGRect newRec4 = [blue convertRect:blue.bounds toView:self.view];
CGPoint newPoint = [red convertPoint:blue.center toView:self.view];

相关文章

网友评论

      本文标题:iOS-convertRect和convertPoint用法

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