坐標(biāo)系轉(zhuǎn)換

相關(guān)方法如下:

  • (CGPoint)convertPoint:(CGPoint)point toView:(nullable UIView *)view;
  • (CGPoint)convertPoint:(CGPoint)point fromView:(nullable UIView *)view;
  • (CGRect)convertRect:(CGRect)rect toView:(nullable UIView *)view;
  • (CGRect)convertRect:(CGRect)rect fromView:(nullable UIView *)view;

判讀兩個(gè)控件是否有重疊

一.當(dāng)兩個(gè)控件共用一個(gè)父控件的時(shí)候,直接通過如下示例判斷
CGRectIntersectsRect(view1.frame, view2.frame)

判斷的2個(gè)函數(shù)如下

  • bool CGRectContainsRect(CGRect rect1, CGRect rect2)
    • 判斷rect1是否包含了rect2
  • bool CGRectIntersectsRect(CGRect rect1, CGRect rect2)
    • 判斷rect1和rect2是否有重疊
    • 注意:rect1和rect2要在同一個(gè)坐標(biāo)系,比較結(jié)果才準(zhǔn)確
二.當(dāng)兩個(gè)控件父控件不相同的時(shí)候

需要先將兩個(gè)控件矩形框轉(zhuǎn)換到同一個(gè)坐標(biāo)原點(diǎn)下,再將轉(zhuǎn)換后的矩形框傳到如下方法中:

CGRectIntersectsRect(rect1, rect2)

轉(zhuǎn)換坐標(biāo)系相關(guān)方法總結(jié)

view2坐標(biāo)系 : 以view2的左上角為坐標(biāo)原點(diǎn)
view1坐標(biāo)系 : 以view1的左上角為坐標(biāo)原點(diǎn)

CGRect newRect = [view1 convertRect:rect fromView:view2];
// 讓rect這個(gè)矩形框, 從view2坐標(biāo)系轉(zhuǎn)換到view1坐標(biāo)系, 得出一個(gè)新的矩形框newRect
// rect和view2的含義 : 用來確定矩形框原來在哪

CGRect newRect = [view1 convertRect:rect toView:view2];
// 讓rect這個(gè)矩形框, 從view1坐標(biāo)系轉(zhuǎn)換到view2坐標(biāo)系, 得出一個(gè)新的矩形框newRect
// rect和view1的含義 :用來確定矩形框原來在哪

獲得一個(gè)控件在window中的位置和尺寸

  • 以獲得redView在window中的位置和尺寸為例
CGRect newRect = [[UIApplication sharedApplication].keyWindow convertRect:redView.bounds fromView:redView];
CGRect newRect = [[UIApplication sharedApplication].keyWindow convertRect:redView.frame fromView:redView.superview];
CGRect newRect = [redView convertRect:redView.bounds toView:[UIApplication sharedApplication].keyWindow];
CGRect newRect = [redView.superview convertRect:redView.frame toView:[UIApplication sharedApplication].keyWindow];
CGRect newRect = [redView convertRect:redView.bounds toView:nil];
CGRect newRect = [redView.superview convertRect:redView.frame toView:nil];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容