2011-11-07 38 views
115

有沒有辦法來驗證CGPoint是否在特定的CGRect內。 例如:我拖着一個UIImageView,我想驗證它的中心點CGPoint是否在另一個UIImageView我該怎麼辦?IOS:驗證點是否在矩形內

回答

239

請參閱文檔中的CGRectContainsPoint()

bool CGRectContainsPoint(CGRect rect, CGPoint point);

參數

  • rect檢查的矩形。
  • point要檢查的一點。 返回值 如果矩形不爲空或空且點位於矩形內,則爲true;否則,是錯誤的。

如果一個點的座標位於矩形的內部或最小的X或最小的Y邊上,則該點被認爲是在矩形內。

+13

缺少的環節;)https://developer.apple.com/library/mac/#documentation/graphicsimaging/reference/CGGeometry/Reference/reference.html – ezekielDFM

+0

救我的時間。謝謝 – HamasN

+0

非常感謝... –

10

UIView的pointInside:withEvent:可能是一個很好的解決方案。 將返回一個布爾值,指示給定的CGPoint是否在您正在使用的UIView實例中。 例子:

UIView *aView = [UIView alloc]initWithFrame:CGRectMake(0,0,100,100); 
CGPoint aPoint = CGPointMake(5,5); 
BOOL isPointInsideView = [aView pointInside:aPoint withEvent:nil]; 
3

它是如此簡單,你可以用下面的方法做這樣的工作: -

-(BOOL)isPoint:(CGPoint)point insideOfRect:(CGRect)rect 
{ 
    if (CGRectContainsPoint(rect,point)) 
     return YES;// inside 
    else 
     return NO;// outside 
} 

在你的情況,你可以通過imagView.center爲點另一個imagView.frame作爲rect in about方法。

您也可以在波紋管UITouch使用此方法方法:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
} 
31

在斯威夫特將是這樣的:

let point = CGPointMake(20,20) 
let someFrame = CGRectMake(10,10,100,100) 
let isPointInFrame = CGRectContainsPoint(someFrame, point) 

斯威夫特3版本:

let point = CGPointMake(20,20) 
let someFrame = CGRectMake(10,10,100,100) 
let isPointInFrame = someFrame.contains(point) 

Link to documentation。請記住檢查遏制,如果兩者是相同的座標系中,如果沒有,那麼轉換需要(some example

+0

非常感謝 –

7

在迅速的,你可以做這樣的:

let isPointInFrame = frame.contains(point) 

「幀」是的CGRect和「點」是一個CGPoint

5

在Objective C中,你可以使用CGRectContainsPoint(yourview.frame,接觸點)

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ 
UITouch* touch = [touches anyObject]; 
CGPoint touchpoint = [touch locationInView:self.view]; 
if(CGRectContainsPoint(yourview.frame, touchpoint)) { 

}else{ 

}} 

快速3 yourview.frame。包含(接觸點)

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    let touch:UITouch = touches.first! 
    let touchpoint:CGPoint = touch.location(in: self.view) 
    if wheel.frame.contains(touchpoint) { 

    }else{ 

    } 

}