當(dāng)我們想找到一個(gè)視圖的子視圖相對(duì)于當(dāng)前控制器中的坐標(biāo)位置時(shí)奥额,用坐標(biāo)轉(zhuǎn)換就可以很方便的找到了瘫拣,如下圖所示:
如圖所示:從下到上依次是 self.view --> redView -->yellowView
redView的坐標(biāo):{{20, 20}, {335, 627}}滚澜,加在控制器的view上
yellowView的坐標(biāo):{{20, 20}, {295, 587}}仰挣,加在redView上
CGSize size = self.view.frame.size;
UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, size.width - 40, size.height - 40)];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
UIImageView *yellowView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, redView.frame.size.width - 40, redView.frame.size.height - 40)];
yellowView.backgroundColor = [UIColor yellowColor];
[redView addSubview:yellowView];
NSLog(@"%@ --- %@", NSStringFromCGRect(redView.frame), NSStringFromCGRect(yellowView.frame));
//? ? 輸出{{20, 20}, {335, 627}} --- {{20, 20}, {295, 587}}
//把 yellowView.frame 從 redView 的坐標(biāo)系轉(zhuǎn)換到 self.view 的坐標(biāo)系
// 如果傳入的是 yellowView.frame舱沧,則要用 yellowView 的父視圖來(lái)調(diào)用溉愁,toView:傳入的參數(shù)是最終要轉(zhuǎn)換到的那個(gè)視圖屋摇。
//? ? CGRect rect = [redView convertRect:yellowView.frame toView:self.view];? ? // 這個(gè)和下面一句一樣
// 如果傳入的是 yellowView.bounds揩魂,則要用 yellowView 本身來(lái)調(diào)用,toView:傳入的參數(shù)是最終要轉(zhuǎn)換到的那個(gè)視圖炮温。
CGRect rect = [yellowView convertRect:yellowView.bounds toView:self.view]; // 這個(gè)和上面一句一樣
CGRect frame = [self.view convertRect:yellowView.frame fromView:redView];
NSLog(@"%@, %@", NSStringFromCGRect(rect), NSStringFromCGRect(frame));
//? ? 輸出{{40, 40}, {295, 587}}, {{40, 40}, {295, 587}}
//把 yellowView.frame.origin 從 redView 的坐標(biāo)系轉(zhuǎn)換到 self.view 的坐標(biāo)系
CGPoint point = [redView convertPoint:yellowView.frame.origin toView:self.view];
CGPoint point1 = [self.view convertPoint:yellowView.frame.origin fromView:redView];
NSLog(@"%@, %@", NSStringFromCGPoint(point), NSStringFromCGPoint(point1));
// 輸出{40, 40}, {40, 40}
?