[cpp] - (void)viewDidLoad
{
[super viewDidLoad];
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(10.0f, 100.0f, 300.0f, 100.0f)];
view1.backgroundColor = [UIColor blackColor];
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(30.0f, 20.0f, 50.0f, 50.0f)];
view2.backgroundColor = [UIColor whiteColor];
[view1 addSubview:view2];
[self.view addSubview:view1];
// converRect: toView
CGRect rect1 = [view1 convertRect:CGRectMake(30.0f, 20.0f, 50.0f, 50.0f) toView:view2]; // 將view1中的frame轉換成在view2中的frame
CGPoint point1 = [view1 convertPoint:CGPointMake(30.0f, 20.0f) toView:view2]; // 將view1中的point轉換成在view2中的point
NSLog(@"rect1:(%f,%f,%f,%f)",rect1.origin.x,rect1.origin.y,rect1.size.width,rect1.size.height);
NSLog(@"point1:(%f,%f)",point1.x,point1.y);
// converRect: fromView
CGRect rect2 = [view2 convertRect:CGRectMake(30.0f, 20.0f, 50.0f, 50.0f) fromView:view1]; // 將view1中的frame轉換成在view2中的frame(同上)
CGPoint point2 = [view2 convertPoint:CGPointMake(30.0f, 20.0f) fromView:view1]; // 將view1中的point轉換成在view2中的point(同上)
NSLog(@"rect2:(%f,%f,%f,%f)",rect2.origin.x,rect2.origin.y,rect2.size.width,rect2.size.height);
NSLog(@"point2:(%f,%f)",point2.x,point2.y);
// 特殊
CGRect rect = [view1 convertRect:CGRectMake(30.0f, 20.0f, 50.0f, 50.0f) toView:nil]; // 這view1中的frame轉換成基於窗口坐標的frame
NSLog(@"rect:(%f,%f,%f,%f)",rect.origin.x,rect.origin.y,rect.size.width,rect.size.height);
[view1 release];
[view2 release];
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(10.0f, 100.0f, 300.0f, 100.0f)];
view1.backgroundColor = [UIColor blackColor];
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(30.0f, 20.0f, 50.0f, 50.0f)];
view2.backgroundColor = [UIColor whiteColor];
[view1 addSubview:view2];
[self.view addSubview:view1];
// converRect: toView
CGRect rect1 = [view1 convertRect:CGRectMake(30.0f, 20.0f, 50.0f, 50.0f) toView:view2]; // 將view1中的frame轉換成在view2中的frame
CGPoint point1 = [view1 convertPoint:CGPointMake(30.0f, 20.0f) toView:view2]; // 將view1中的point轉換成在view2中的point
NSLog(@"rect1:(%f,%f,%f,%f)",rect1.origin.x,rect1.origin.y,rect1.size.width,rect1.size.height);
NSLog(@"point1:(%f,%f)",point1.x,point1.y);
// converRect: fromView
CGRect rect2 = [view2 convertRect:CGRectMake(30.0f, 20.0f, 50.0f, 50.0f) fromView:view1]; // 將view1中的frame轉換成在view2中的frame(同上)
CGPoint point2 = [view2 convertPoint:CGPointMake(30.0f, 20.0f) fromView:view1]; // 將view1中的point轉換成在view2中的point(同上)
NSLog(@"rect2:(%f,%f,%f,%f)",rect2.origin.x,rect2.origin.y,rect2.size.width,rect2.size.height);
NSLog(@"point2:(%f,%f)",point2.x,point2.y);
// 特殊
CGRect rect = [view1 convertRect:CGRectMake(30.0f, 20.0f, 50.0f, 50.0f) toView:nil]; // 這view1中的frame轉換成基於窗口坐標的frame
NSLog(@"rect:(%f,%f,%f,%f)",rect.origin.x,rect.origin.y,rect.size.width,rect.size.height);
[view1 release];
[view2 release];
}輸出結果:
結論:
1、A convert xxx to B / B convert xxx from A 將視圖A中的坐標系統轉換成視圖B中的坐標系統;
2、A convert xxx to B,B為nil時將視圖A中的坐標系統轉換成窗口的坐標系統。