坐標(biāo)系轉(zhuǎn)換.png
一咖气、首先來看看一下我們的需求
- 將
yellowView
(黃色view)所在的frame轉(zhuǎn)換為blueView
(藍(lán)色view)所在的frame
二、廢話不多說汗洒,直接上代碼代碼
- 首先我們創(chuàng)建三個(gè)view议纯,并且讓
redView
作為blueView
子view,yellowView
作為redView
子view
// 創(chuàng)建blueView
UIView *blueView = [[UIView alloc] init];
blueView.backgroundColor = [UIColor blueColor];
blueView.frame = CGRectMake(30, 30, 200, 200);
[self.view addSubview:blueView];
self.blueView = blueView;
// 創(chuàng)建redView
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
redView.frame = CGRectMake(10, 20, 100, 100);
[blueView addSubview:redView];
self.redView = redView;
// 創(chuàng)建yellowView
UIView *yellowView = [[UIView alloc] init];
yellowView.backgroundColor = [UIColor yellowColor];
yellowView.frame = CGRectMake(10, 20, 50, 50);
[redView addSubview:yellowView];
self.yellowView = yellowView;
顯示的結(jié)果就是上面的截圖
- 重寫控制器的
touchesBegan:withEvent:
方法
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"oldFrame -- %@", NSStringFromCGRect(self.yellowView.frame));
}
打印原始yellowView
frame為:
原始frame.png
開始坐標(biāo)系轉(zhuǎn)換
- 使用
convertRect:toView:
轉(zhuǎn)換坐標(biāo)系
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 獲取self.yellowView 在self.blueView 的坐標(biāo)
CGRect newFrame = [self.yellowView convertRect:self.yellowView.bounds toView:self.blueView];
NSLog(@"%@", NSStringFromCGRect(newFrame));
}
可以看到打印結(jié)果為:
轉(zhuǎn)換后的frame.png
- 我們也可以借助
redView
為突破點(diǎn)
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 獲取self.yellowView 在self.blueView 的坐標(biāo)
// CGRect newFrame = [self.yellowView convertRect:self.yellowView.bounds toView:self.blueView];
// 這句話可以理解為:self.yellowView.frame是在redView坐標(biāo)系溢谤,所以轉(zhuǎn)換的時(shí)候瞻凤,得使用self.redView
CGRect newFrame = [self.yellowView.superview convertRect:self.yellowView.frame toView:self.blueView];
NSLog(@"%@", NSStringFromCGRect(newFrame));
}
- 使用
convertRect:fromView:
轉(zhuǎn)換坐標(biāo)系
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 獲取self.yellowView 在self.blueView 的坐標(biāo)
// CGRect newFrame = [self.yellowView convertRect:self.yellowView.bounds toView:self.blueView];
// 這句話可以理解為:self.yellowView.frame是在redView坐標(biāo)系憨攒,所以轉(zhuǎn)換的時(shí)候,得使用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));
}
可以看到阀参,打印結(jié)果是一樣的
坐標(biāo)轉(zhuǎn)換.png
總結(jié)
convertRect:toView:
就是將某個(gè)view的frame轉(zhuǎn)為toView
的frame
convertRect:fromView:
就是從fromView
的frame轉(zhuǎn)為調(diào)用這個(gè)方法的view的frame