坐标系的转换

2020-04-15  本文已影响0人  冷武橘
0CE02AD6-5C7C-4A42-B672-D6B85E492AC4.png

首先用代码创建如图所示的图层:
UIView *redview=[[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
redview.backgroundColor=[UIColor redColor];
[self.view addSubview:redview];
UIView *blueview=[[UIView alloc]initWithFrame:CGRectMake(50, 50, 100, 100)];
blueview.backgroundColor=[UIColor blueColor];
[redview addSubview:blueview];
如上图的红色View,以控制器的view为父控件作为坐标系原点,那么它的frame的x = 100,y = 100;而蓝色view是以红色view作为坐标系原点,那么他的frame x=50,y=50;有时为了比较两个view是否重叠,或者相对于主窗口获取位置等就需要将两者坐标系转换成同一个坐标系。主要通过以下两个方法进行转换:

 //rect用来确定矩形框原来位置
 (CGRect)convertRect:(CGRect)rect toView:(nullable UIView *)view;
 (CGRect)convertRect:(CGRect)rect fromView:(nullable UIView *)view;

  //让rect这个矩形框,从view2坐标系转换到view1坐标系,得出一个新的矩形框newrect
 [view1 converRect:rect fromview:view2]

//让rect这个矩形框,从view1坐标系转换到view2坐标系,得出一个新的矩形框newrect
 [view1 convertRect:rect toView:view2]
 //确定blueview在self.view的frame的四种方式:
    CGRect newrect= [self.view convertRect:blueview.frame fromView:redview];
    NSLog(@"%@",NSStringFromCGRect(newrect));

    CGRect newrect= [self.view convertRect:blueview.bounds fromView:blueview];
    NSLog(@"%@",NSStringFromCGRect(newrect));

    CGRect newrect= [redview convertRect:blueview.frame toView:self.view];
    NSLog(@"%@",NSStringFromCGRect(newrect));

    CGRect newrect= [blueview convertRect:blueview.bounds toView:self.view];
    NSLog(@"%@",NSStringFromCGRect(newrect));

将控件的位置转换到主窗口:

//传nil后进去会默认转换到主窗口
[blueview convertRect:blueview.bounds toView:nil];

//常用
[blueview convertRect:blueview.bounds toView:[UIApplication sharedApplication].keyWindow];

[[UIApplication sharedApplication].keyWindow convertRect:blueview.bounds fromView:blueview];

[blueview convertRect:blueview.superview.frame toView:[UIApplication sharedApplication].keyWindow];

[blueview convertRect:redview.frame toView:[UIApplication sharedApplication].keyWindow];

 [[UIApplication sharedApplication].keyWindow convertRect:redview.frame fromView:blueview];
上一篇下一篇

猜你喜欢

热点阅读