iOS坐标系统以及转换方法

首先非常感谢陈董Don – iOS工程师的开源文章iOS 座标系统以及转换方法,文章是用swift写的,我在学习的时候就顺手转成了OC版本,记录一下学习过程.

IOS的坐标系统:要说明这个问题,首先必须理清frame与bounds的区别.
frame的值是根据superView的坐标系统而定,superView的左上角为原点(0,0).例如下面三个视图,控制器本身的View是blueView的superView,blueView是redView的superView,redView是greenView的superView.
bounds的值是根据自身的坐标体统而定,即初始化状态自身左上角为原点(0,0).

UIView *blueView = [[UIView alloc] initWithFrame:CGRectMake(40, 40, 250, 250)];
blueView.backgroundColor = [UIColor blueColor];
[self.view addSubview:blueView];

UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(40, 40, 150, 150)];
redView.backgroundColor = [UIColor redColor];
[blueView addSubview:redView];

UIView *greenView = [[UIView alloc] initWithFrame:CGRectMake(40, 40, 50, 50)];
greenView.backgroundColor = [UIColor greenColor];
[redView addSubview:greenView];

如上代码中,blueView的frame是(40, 40, 150, 150),而greenView的frame是(40, 40, 50, 50),x和y的坐标是一样的,是因为他们所在的superView不同.
blueView的bounds是(0, 0, 150, 150),greenView的bounds是(0, 0, 50, 50),x和y的坐标都是0,是因为bounds是根据他们自身的左上角为原点来计算的.

下面我们说坐标转换:
我们可以试想一下,如何得到greenView在self.view中的坐标呢?
有以下几个方法可以实现不同坐标系之间的图层转换

 // 将像素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;

用下面的方法可以解决我们所提出的问题:

CGRect convertFrame;
convertFrame = [blueView convertRect:greenView.frame fromView:redView];
convertFrame = [redView convertRect:greenView.frame toView:self.view];
NSLog(@"convertFrame:%@",NSStringFromCGRect(convertFrame));

顺便提一句:在iOS开发中,view的frame,是CGRect类型的,用frame.size.width来做NSLog参数非常麻烦。苹果对这些常用的数据提供了字符串转换的方法。

 NSString *NSStringFromCGPoint( CGPoint point);
 NSString *NSStringFromCGSize( CGSize size);
 NSString *NSStringFromCGRect( CGRect rect);
 NSString *NSStringFromCGAffineTransform( CGAffineTransform transform);
 NSString *NSStringFromUIEdgeInsets( UIEdgeInsets insets);
 NSString *NSStringFromUIOffset( UIOffset offset);

这样就可以轻松打印出frame了.

我们怎么判断是否包含某个视图呢?

BOOL isContain = NO;
isContain = [self.view.subviews containsObject:blueView];
NSLog(@"isContain:%@",isContain?@"YES":@"NO");
isContain = [blueView.subviews containsObject:redView];
NSLog(@"isContain:%@",isContain?@"YES":@"NO");
isContain = [redView.subviews containsObject:greenView];
NSLog(@"isContain:%@",isContain?@"YES":@"NO");

这三个打印结果都是YES.

2017-03-22 11:29:07.627450 ZYYTabBar[616:211841] convertFrame:{{120, 120}, {50, 50}}
2017-03-22 11:29:07.627580 ZYYTabBar[616:211841] isContain:YES
2017-03-22 11:29:07.627645 ZYYTabBar[616:211841] isContain:YES
2017-03-22 11:29:07.627701 ZYYTabBar[616:211841] isContain:YES

好了,就说到这里吧,再次感谢陈董Don – iOS工程师的开源!

你可能感兴趣的:(iOS坐标系统以及转换方法)