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

// 將像素point由point所在視圖轉(zhuǎn)換到目標(biāo)視圖view中,返回在目標(biāo)視圖view中的像素值

- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;

// 將像素point從view中轉(zhuǎn)換到當(dāng)前視圖中,返回在當(dāng)前視圖中的像素值

- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;

// 將rect由rect所在視圖轉(zhuǎn)換到目標(biāo)視圖view中,返回在目標(biāo)視圖view中的rect

- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;

// 將rect從view中轉(zhuǎn)換到當(dāng)前視圖中,返回在當(dāng)前視圖中的rect

- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;

例把UITableViewCell中的subview(btn)的frame轉(zhuǎn)換到controllerA中


// controllerA 中有一個(gè)UITableView, UITableView里有多行UITableVieCell,cell上放有一個(gè)button

// 在controllerA中實(shí)現(xiàn):

CGRect rc = [cell convertRect:cell.btn.frame toView:self.view];

CGRect rc = [self.view convertRect:cell.btn.frame fromView:cell];

// 此rc為btn在controllerA中的rect

或當(dāng)已知btn時(shí):

CGRect rc = [btn.superview convertRect:btn.frame toView:self.view];

CGRect rc = [self.view convertRect:btn.frame fromView:btn.superview];



UIView*greenView = [[UIViewalloc]initWithFrame:CGRectMake(10, 20, 100, 100)];

greenView.backgroundColor= [UIColorgreenColor];

[self.viewaddSubview:greenView];

UIView*redView = [[UIViewalloc]initWithFrame:CGRectMake(110, 120, 200, 200)];

redView.backgroundColor= [UIColorredColor];

[self.viewaddSubview:redView];

UIView*blueView = [[UIViewalloc]initWithFrame:CGRectMake(10, 20, 100, 100)];

[redViewaddSubview:blueView];

blueView.backgroundColor= [UIColorblueColor];

CGRectframe= [redViewconvertRect:blueView.frametoView:greenView];

UIView*overLapView1 = [[UIViewalloc]initWithFrame:frame];

[self.viewaddSubview:overLapView1];

overLapView1.backgroundColor= [UIColororangeColor];



在開發(fā)中我們經(jīng)常會(huì)需要判斷兩個(gè)控件是否包含重疊,此時(shí)如果控件A和B的坐標(biāo)原點(diǎn)如果不確定的話,那么肯定會(huì)導(dǎo)致比較不正確發(fā)生錯(cuò)誤

判斷包含重疊的代碼如下:

CGRectContainsRect(<#CGRect rect1#>, <#CGRect rect2#>)

CGRectContainsPoint(<#CGRect rect#>, <#CGPoint point#>)

CGRectIntersectsRect(<#CGRect rect1#>, <#CGRect rect2#>)

其中

CGRectContainsRect表示rect1和rect2是否有重疊

CGRectContainsPoint表示point是不是在rect上

CGRectIntersectsRect的意思是rect1是否包含了rect2


那么問題就來了,既然坐標(biāo)原點(diǎn)不確定,那么能不能轉(zhuǎn)換A的坐標(biāo)原點(diǎn)到B上呢?答案是可以的,具體實(shí)現(xiàn)代碼如下:

- (CGPoint)convertPoint:(CGPoint)point toView:(nullableUIView*)view;- (CGPoint)convertPoint:(CGPoint)point fromView:(nullableUIView*)view;// 后面就具體使用下面的代碼舉例,下面的會(huì)了,上面的自然也就會(huì)了- (CGRect)convertRect:(CGRect)rect toView:(nullableUIView*)view;- (CGRect)convertRect:(CGRect)rect fromView:(nullableUIView*)view;

最后編輯于
?著作權(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),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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