好长时间不用,发现对 UIView中的坐标转换已经没有印象了,突然发现自己不会用了,<不对,好像以前也没咋弄懂~~~~~>
下面自己来总结下:
直接看代码输出和解释,是不是一目了然啊~~~~我都懂了,你们看了都会懂啦...嘿嘿!!!
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom]; // rightButton的原始坐标 rightButton.frame = CGRectMake(200, 100, 100, 50); [rightButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal]; rightButton.backgroundColor=[UIColor redColor]; [rightButton setTitle:@"完成" forState:UIControlStateNormal]; [self.view addSubview:rightButton]; /* 1.将像素point从view中转换到当前视图中,返回在当前视图中的像素值 输出: point = 0.000000---0.000000 CGPoint point = [rightButton convertPoint:CGPointMake(200, 100) fromView:self.view]; rightButton.frame = CGRectMake(point.x, point.y, 100, 50); NSLog(@"point = %f---%f",point.x,point.y); */ /*2.将像素point由point所在视图转换到目标视图view中,返回在目标视图view中的像素值 输出: point = 300.000000---200.000000 CGPoint point = [rightButton convertPoint:CGPointMake(100,100) toView:self.view]; rightButton.frame = CGRectMake(point.x, point.y, 100, 50); NSLog(@"point = %f---%f",point.x,point.y); */ /* 3.将rect由rect所在视图转换到目标视图view中,返回在目标视图view中的rect 输出: 220.000000--120.000000--20.000000--20.000000 CGRect rect = [rightButton convertRect:CGRectMake(20, 20, 20, 20) toView:self.view]; rightButton.frame = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); NSLog(@"%f--%f--%f--%f",rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); */ /* 4.将rect由rect所在视图转换到目标视图view中,返回在目标视图view中的rect 输出: -180.000000---80.000000--20.000000--20.000000 */ CGRect rect = [rightButton convertRect:CGRectMake(20, 20, 20, 20) fromView:self.view]; rightButton.frame = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); NSLog(@"%f--%f--%f--%f",rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); } @end
我自己总结记住的就是:
// 将像素point由point所在视图转换到目标视图view中,返回在目标视图view中的像素值
- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view; // 坐标点相加
// 将像素point从view中转换到当前视图中,返回在当前视图中的像素值
- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view; // 坐标点相减,并且是新坐标点 - 原坐标点
// 将rect由rect所在视图转换到目标视图view中,返回在目标视图view中的rect
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view; // 坐标点相加,改变原始宽高
// 将rect从view中转换到当前视图中,返回在当前视图中的rect
- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view; // 坐标点相减,并且是新坐标点 - 原坐标点,改变原始宽高