当前位置: 代码迷 >> 综合 >> iOS-UIView坐标系转换-(convertRect toView/convertRect fromView)
  详细解决方案

iOS-UIView坐标系转换-(convertRect toView/convertRect fromView)

热度:20   发布时间:2024-01-12 04:39:15.0
视图

在这里插入图片描述

- (void)demo{UIView *greenView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];greenView.backgroundColor =[UIColor greenColor];[self.view addSubview:greenView];UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];redView.backgroundColor =[UIColor redColor];[greenView addSubview:redView];CGRect rect1 = [greenView convertRect:redView.frame toView:self.view];CGRect rect2 = [greenView convertRect:redView.frame toView:greenView];CGRect rect3 = [self.view convertRect:redView.frame fromView:greenView];NSLog(@"rect1 frame:%@",NSStringFromCGRect(rect1));NSLog(@"rect2 frame:%@",NSStringFromCGRect(rect2));NSLog(@"rect3 frame:%@",NSStringFromCGRect(rect3));
}
打印结果:
2018-10-12 09:35:14.933665+0800 demo[1996:45087] rect1 frame:{
   {20, 20}, {100, 100}}
2018-10-12 09:35:14.933913+0800 demo[1996:45087] rect2 frame:{
   {10, 10}, {100, 100}}
2018-10-12 09:35:14.934041+0800 demo[1996:45087] rect3 frame:{
   {20, 20}, {100, 100}}
注意
//Converts a rectangle from the receiver’s coordinate system to that of another view
[view1 convertRect:view2.frame toView:view3]
注意:view1是view2的父视图,即view2的frame是相对于view1的(view1一般是scrollview)
view3这里认为是view1的父视图,可以得到滚动过程中view2相对于view3的frame//Converts a rectangle from the coordinate system of another view to that of the receiver.
[view3 convertRect:view2.frame fromView:view1]这么写和上面代码的结果是一样的