iOS開發筆記--UIView中的坐標轉換(convertRect)


 

// 將像素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;
// controllerA 中有一個UITableView, UITableView里有多行UITableVieCell,cell上放有一個button
// 在controllerA中實現:
CGRect rc = [cell convertRect:cell.btn.frame toView:self.view];
或
CGRect rc = [self.view convertRect:cell.btn.frame fromView:cell];
// 此rc為btn在controllerA中的rect

或當已知btn時:
CGRect rc = [btn.superview convertRect:btn.frame toView:self.view];
或
CGRect rc = [self.view convertRect:btn.frame fromView:btn.superview];

轉摘自:http://blog.csdn.net/xuhuan_wh/article/details/8486337

心得:仔細理會有其道理,哪個view上的尺寸,要到哪個view上去挖相同的尺寸(總之相對於屏幕位置不變)。總之就是一個View轉換到另一個View,就是直接將要轉換的Frame往外面凸起或者凹進去,到目標View上對應的尺寸

eg:

UIScrollView *ss= [[UIScrollView alloc]initWithFrame:self.view.bounds];
    ss.backgroundColor=[UIColor whiteColor];
    ss.contentSize=CGSizeMake(ss.frame.size.width, ss.frame.size.height*2);
    //原始View
    UIView *vv=[[UIView alloc]initWithFrame:CGRectMake(100, 580, 100, 40)];
    vv.backgroundColor=[UIColor redColor];
    [ss addSubview:vv];
    [self.view addSubview:ss];
    
    //目標View
    UIView *backgroundView=[[UIView alloc]initWithFrame:CGRectMake(0, 100, 320, 100)];
    backgroundView.backgroundColor=[UIColor brownColor];
    [self.view addSubview:backgroundView];
    //原始View的尺寸要映射到目標View上返回其尺寸
    CGRect rect=[vv convertRect:vv.bounds toView:backgroundView];
    NSLog(@"%@",NSStringFromCGRect(rect));
    CGRect rect1=[backgroundView convertRect:vv.bounds fromView:vv];
    NSLog(@"%@",NSStringFromCGRect(rect1));
輸出結果:2015-02-05 10:02:10.301 testConvertRect[1262:27344] {{100, 480}, {100, 40}}
        2015-02-05 10:02:10.302 testConvertRect[1262:27344] {{100, 480}, {100, 40}}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM