UIView中的坐标转换

- (CGPoint)convertPoint:(CGPoint)point toView:(nullable UIView *)view;

- (CGPoint)convertPoint:(CGPoint)point fromView:(nullable UIView *)view;

- (CGRect)convertRect:(CGRect)rect toView:(nullable UIView *)view;

- (CGRect)convertRect:(CGRect)rect fromView:(nullable UIView *)view;

主要是用来自动计算不同层级下的CGPoint,UIView之间的坐标转换。


例子:

UIView中的坐标转换_第1张图片

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

NSLog(@"%@",NSStringFromCGRect(rec));

这句代码的意思是灰色View中的黄色View相对于self.view中的位置



CGRect newRect = [self.yellowView convertRect:CGRectMake(50, 50, 20, 20) toView:self.blueView];

这句代码的意思是在黄色View中,定义一个相对于黄色View(50,50),大小为(20,20)的View,这个View相对于蓝色View的位置



需要注意的是:ToView是可以传nil的

CGRect newRect = [self.yellowView convertRect:CGRectMake(50, 50, 20, 20) toView:nil];

这句代码的意思是在黄色View中,定义一个目标区域,该区域相对于window的位置(nil代表的是self.view.window



下面来展示三个方法如何做到黄色View在Window中的位置

前两种(ToView)

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

CGRect newRect = [self.greyView convertRect:self.yellowView.frame toView:nil];

这样也正好表明了frame和bounds的区别,第一段代码表示,在yellowView中,有个

和yellowView一样的大小的区域bounds,此区域相对于window的位置,而第二段代码

表示,在greyView中,其子视图yellowView的frame区域,相对于window的位置


第三种(FromView)

CGRect rec1 = [self.view.window convertRect:self.yellowView.bounds fromView:self.yellowView];



总结:

toView就是从左往右开始读代码,也是从左往右理解意思

fromView就是从右往左开始读代码,也是从右往左理解意思

- A(CGPoint)convertPoint:B(CGPoint)point toView:C(nullable UIView *)view;

- A(CGPoint)convertPoint:B(CGPoint)point fromView:C(nullable UIView *)view;

第一句代表

A区域里面有个坐标B,需要把相对于A的坐标B转换成相对于C的坐标

第二句代表

从C区域里面转换坐标B,需要把相对于C的坐标转换成相对于A的坐标

理解下用起来真的蛮不错哦

你可能感兴趣的:(UIView中的坐标转换)