- (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中的坐标系统转换成窗口的坐标系统。