iOS坐标系转换

2016-01-10  本文已影响0人  hj的简书
坐标系转换.png

一、首先来看看一下我们的需求

二、废话不多说,直接上代码代码

    // 创建blueView
    UIView *blueView = [[UIView alloc] init];
    blueView.backgroundColor = [UIColor blueColor];
    blueView.frame = CGRectMake(30, 30, 200, 200);
    [self.view addSubview:blueView];
    self.blueView = blueView;
    
    // 创建redView
    UIView *redView = [[UIView alloc] init];
    redView.backgroundColor = [UIColor redColor];
    redView.frame = CGRectMake(10, 20, 100, 100);
    [blueView addSubview:redView];
    self.redView = redView;
    
    // 创建yellowView
    UIView *yellowView = [[UIView alloc] init];
    yellowView.backgroundColor = [UIColor yellowColor];
    yellowView.frame = CGRectMake(10, 20, 50, 50);
    [redView addSubview:yellowView];
    self.yellowView = yellowView;

显示的结果就是上面的截图

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"oldFrame -- %@", NSStringFromCGRect(self.yellowView.frame));
}

打印原始yellowViewframe为:

原始frame.png

开始坐标系转换

  1. 使用convertRect:toView:转换坐标系
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 获取self.yellowView 在self.blueView 的坐标
    
    CGRect newFrame = [self.yellowView convertRect:self.yellowView.bounds toView:self.blueView];
    NSLog(@"%@", NSStringFromCGRect(newFrame));
}

可以看到打印结果为:


转换后的frame.png

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 获取self.yellowView 在self.blueView 的坐标
//    CGRect newFrame = [self.yellowView convertRect:self.yellowView.bounds toView:self.blueView];
    
    // 这句话可以理解为:self.yellowView.frame是在redView坐标系,所以转换的时候,得使用self.redView
    CGRect newFrame = [self.yellowView.superview convertRect:self.yellowView.frame toView:self.blueView];
    
    NSLog(@"%@", NSStringFromCGRect(newFrame));
}
  1. 使用convertRect:fromView:转换坐标系
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 获取self.yellowView 在self.blueView 的坐标
//    CGRect newFrame = [self.yellowView convertRect:self.yellowView.bounds toView:self.blueView];
    
    // 这句话可以理解为:self.yellowView.frame是在redView坐标系,所以转换的时候,得使用self.redView
//    CGRect newFrame = [self.yellowView.superview convertRect:self.yellowView.frame toView:self.blueView];
    
    CGRect newFrame = [self.blueView convertRect:self.yellowView.bounds fromView:self.yellowView];
    
    NSLog(@"%@", NSStringFromCGRect(newFrame));
}

可以看到,打印结果是一样的

坐标转换.png

总结

convertRect:toView:就是将某个view的frame转为toView的frame
convertRect:fromView:就是从fromView的frame转为调用这个方法的view的frame

上一篇下一篇

猜你喜欢

热点阅读