IOS:验证一个点是否在矩形内

Cra*_*Dev 138 collision-detection uiview cgpoint ios cgrect

有没有办法验证a CGPoint是否在特定内部CGRect.例如:我正在拖动一个UIImageView,我想验证它的中心点CGPoint是否在另一个内部UIImageView我该怎么办?

Ole*_*ann 290

迅速

用途CGRectContainsPoint():

let view = ...
let point = ...
view.bounds.contains(point)
Run Code Online (Sandbox Code Playgroud)

Objective-C的

用途bool CGRectContainsPoint(CGRect rect, CGPoint point);:

rect

参数

  • point 要检查的矩形.
  • CGRectContainsPoint() 要检查的要点.返回值如果矩形不为null或为空且该点位于矩形内,则返回true;否则返回false.否则,错误.

如果点的坐标位于矩形内或最小X或最小Y边上,则在矩形内部考虑一个点.

  • 缺少的链接;)https://developer.apple.com/library/mac/#documentation/graphicsimaging/reference/CGGeometry/Reference/reference.html (13认同)
  • 在Swift 3.0中使用如下:rect =视图的框架,然后是isContain = rect.contains(point) (5认同)

Jul*_*ról 38

在Swift中看起来像这样:

let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = CGRectContainsPoint(someFrame, point)
Run Code Online (Sandbox Code Playgroud)

Swift 3版本:

let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = someFrame.contains(point)
Run Code Online (Sandbox Code Playgroud)

链接到文档.如果两者都在同一坐标系中,请记得检查遏制,否则需要进行转换(例如)


Sta*_*ash 12

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];
Run Code Online (Sandbox Code Playgroud)


Chu*_*y47 10

在swift中你可以这样做:

let isPointInFrame = frame.contains(point)
Run Code Online (Sandbox Code Playgroud)

"frame"是CGRect,"point"是CGPoint


小智 5

在目标c中,您可以使用CGRectContainsPoint(yourview.frame,touchpoint)

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

}else{

}}
Run Code Online (Sandbox Code Playgroud)

在swift 3中你的view.frame.contains(接触点)

 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{

    }

}
Run Code Online (Sandbox Code Playgroud)