UIView中的座標轉換

2021-07-07 11:01:18 字數 2900 閱讀 3081

今天使用cgrectcontainsrect方法時,出現了一些問題,現在總結一下:

首先了解一下一些基本的方法:

cgrectcontainsrect(cgrect rect1, cgrect rect2)  判斷rect1是否包含rect2

cgrectcontainspoint(cgrect rect, cgpoint point) 判斷point是不是在rect上

cgrectintersectsrect(cgrect rect1, cgrect rect2) 判斷兩個區域是否相交

cgrectintersection (cgrect r1,cgrect r2); 兩個矩形的相交的矩形區域

cgpointequaltopoint(); 兩個點是否是乙個點

cgsizeequaltosize(); 兩個size是否一樣

cgrectinset(cgrect rect, cgfloat dx, cgfloat dy) 根據乙個矩形的中心點來建立矩形,正值是建立比較小的矩形,負值是建立比較大的矩形.

然後看 demo:

首先我通過storyboard給檢視控制器的 view 新增3個 view, 如下圖:

然後建立關聯,分別得到對應的 view.然後並編寫相應**如下:

#import "viewcontroller.h"

@inte***ce

viewcontroller ()

@property (weak, nonatomic) iboutlet

uiview *blueview;

@property (weak, nonatomic) iboutlet

uiview *redview;

@property (weak, nonatomic) iboutlet

uiview *yellowview;

@end

@implementation

viewcontroller

- (void)viewdidload

-(void)test1else

if (cgrectcontainsrect(self

.redview

.frame,self

.blueview

.frame)) else

if (cgrectcontainsrect(self

.redview

.frame,self

.yellowview

.frame)) else

nslog(@"%@ %@ %@",nsstringfromcgrect(self

.redview

.frame),nsstringfromcgrect(self

.blueview

.frame),nsstringfromcgrect(self

.yellowview

.frame));

}@end

結果為:紅色檢視與藍色相交! 紅色檢視不包含藍色檢視! 紅色檢視包含黃色檢視!

, } , } , }

一看結果,為什麼啊!blueview和yellowview都是新增到redview上啊,怎麼會乙個包含,乙個不包含啊!,但是不知道你有沒有注意到列印出來的 frame有什麼問題沒?現在就進入主題了,uiview中的座標轉換.先看**:

cgrect newframe = [self.redview convertrect:self.blueview.frame toview:self.view];

nslog(@"newframe: %@",nsstringfromcgrect(newframe));

if (cgrectcontainsrect(self.redview.frame,newframe)) else

結果為:紅色檢視包含藍色檢視!   newframe: , }. 

那麼現在結果就對了,所以關鍵就在於檢視相對的座標系不一樣.所以要把blueview變換到當前座標系.

還記得剛學 frame 和 bounds的時候,由於ui控制項的frame屬性都是依據該控制項的父控制項原點作為座標系原點(0,0)的,所以,當父控制項不是控制器view時,無法根據ui控制項的frame來獲取其相對於控制器view的位置。在實際開發中,為了獲取某個子控制項相對於螢幕頂部/底部/左邊/右邊的實際距離,必須要去改變子控制項的座標系。

以下是一些常用的轉換方法:

將畫素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;

- - 注:若view引數為空,則轉換為視窗(window)的座標系;接收者與view都必須是同一視窗(window)的物件。

UIView中的座標轉換

將畫素point由point所在檢視轉換到目標檢視view中,返回在目標檢視view中的畫素值 cgpoint convertpoint cgpoint point toview uiview view 將畫素point從view中轉換到當前檢視中,返回在當前檢視中的畫素值 cgpoint conv...

UIView中的座標轉換

將畫素point由point所在檢視轉換到目標檢視view中,返回在目標檢視view中的畫素值 將畫素point由point所在檢視轉換到目標檢視view中,返回在目標檢視view中的畫素值 cgpoint convertpoint cgpoint point toview uiview view ...

UIView相對座標轉換

有時候要在view裡,要求a相對於b的位置,可用uiview提供的以下函式 convertrect toview cgrect convertrect cgrect rect toview uiview view 轉換呼叫者檢視中的某個矩形,轉換為相對於view的矩形座標 convertrect f...