美文网首页精品文章
iOS坐标系转换 convertRect

iOS坐标系转换 convertRect

作者: 69a8e4612fc7 | 来源:发表于2016-10-24 11:38 被阅读116次

当我们想找到一个视图的子视图相对于当前控制器中的坐标位置时,用坐标转换就可以很方便的找到了,如下图所示:


如图所示:从下到上依次是 self.view --> redView -->yellowView

redView的坐标:{{20, 20}, {335, 627}},加在控制器的view上

yellowView的坐标:{{20, 20}, {295, 587}},加在redView上

CGSize size = self.view.frame.size;

UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, size.width - 40, size.height - 40)];

redView.backgroundColor = [UIColor redColor];

[self.view addSubview:redView];

UIImageView *yellowView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, redView.frame.size.width - 40, redView.frame.size.height - 40)];

yellowView.backgroundColor = [UIColor yellowColor];

[redView addSubview:yellowView];

NSLog(@"%@ --- %@", NSStringFromCGRect(redView.frame), NSStringFromCGRect(yellowView.frame));

//    输出{{20, 20}, {335, 627}} --- {{20, 20}, {295, 587}}

//把 yellowView.frame 从 redView 的坐标系转换到 self.view 的坐标系

// 如果传入的是 yellowView.frame,则要用 yellowView 的父视图来调用,toView:传入的参数是最终要转换到的那个视图。

//    CGRect rect = [redView convertRect:yellowView.frame toView:self.view];    // 这个和下面一句一样

// 如果传入的是 yellowView.bounds,则要用 yellowView 本身来调用,toView:传入的参数是最终要转换到的那个视图。

CGRect rect = [yellowView convertRect:yellowView.bounds toView:self.view]; // 这个和上面一句一样

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

NSLog(@"%@, %@", NSStringFromCGRect(rect), NSStringFromCGRect(frame));

//    输出{{40, 40}, {295, 587}}, {{40, 40}, {295, 587}}

//把 yellowView.frame.origin 从 redView 的坐标系转换到 self.view 的坐标系

CGPoint point = [redView convertPoint:yellowView.frame.origin toView:self.view];

CGPoint point1 = [self.view convertPoint:yellowView.frame.origin fromView:redView];

NSLog(@"%@, %@", NSStringFromCGPoint(point), NSStringFromCGPoint(point1));

// 输出{40, 40}, {40, 40}

 

相关文章

网友评论

    本文标题:iOS坐标系转换 convertRect

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