如你所知,iOS中坐標系轉(zhuǎn)換,需要使用以下兩個系統(tǒng)API。
- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;
本文將詳細講述兩個API的具體使用方法及含義。
-
convertRect: fromView:
- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;
// 轉(zhuǎn)換viewB坐標系內(nèi)區(qū)域rect,在viewA坐標系中的區(qū)域。
CGRect rect = viewB.bounds;
CGRect result = [viewA convertRect:rect fromView:viewB];
viewB坐標系內(nèi)區(qū)域rect,在viewA坐標系中的區(qū)域。
上述方法rect取的是viewB.bounds的值,因此又可以描述為:
viewB在viewA內(nèi)部坐標系中的區(qū)域。
-
convertRect: toView:
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;
// 轉(zhuǎn)換viewA坐標系內(nèi)區(qū)域rect,在viewB坐標系中的區(qū)域。
CGRect rect = viewA.bounds;
CGRect result = [viewA convertRect:rect toView:viewB];
上述方法rect取的是viewA.bounds的值,因此又可以描述為:
viewA在viewB內(nèi)部坐標系中的區(qū)域。
-
常見誤區(qū)
rect 參數(shù)的使用經(jīng)常會出現(xiàn)錯誤:
CGRect result_false = [viewA convertRect:viewA.frame toView:viewB]; 錯誤:?
CGRect result_right = [viewA convertRect:viewA.frame toView:viewB]; 正確:?
result_false 為,viewA坐標系中frame位置,應設在viewB坐標系中的區(qū)域。
相對result_right 來說,result_false的origin會附加viewA.frame.origin的值。