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

视图

在这里插入图片描述

- (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]这么写和上面代码的结果是一样的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值