有没有一种方法可以验证一个CGPoint
是否在特定的CGRect
内?
一个示例是:我正在拖动一个UIImageView
,我想验证它的中心点CGPoint
是否在另一个UIImageView
中。
有没有一种方法可以验证一个CGPoint
是否在特定的CGRect
内?
一个示例是:我正在拖动一个UIImageView
,我想验证它的中心点CGPoint
是否在另一个UIImageView
中。
let view = ...
let point = ...
view.bounds.contains(point)
bool CGRectContainsPoint(CGRect rect, CGPoint point);
参数
rect
要检查的矩形。point
要检查的点。
返回值
如果矩形不为null或空且点位于矩形内,则返回true;否则,返回false。如果一个点的坐标在矩形内或者在最小的X或Y边缘上,该点将被视为在矩形内部。
在 Swift 中,它看起来像这样:
let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = CGRectContainsPoint(someFrame, point)
Swift 3 版本:
let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = someFrame.contains(point)
在 Swift 中,你可以这样做:
let isPointInFrame = frame.contains(point)
"frame"是一个CGRect类型,而"point"是一个CGPoint类型。
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];
在Objective-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{
}}
In swift 3 yourview.frame.contains(touchpoint)
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{
}
}
操作很简单,您可以使用以下的方法来完成这项工作:
-(BOOL)isPoint:(CGPoint)point insideOfRect:(CGRect)rect
{
if ( CGRectContainsPoint(rect,point))
return YES;// inside
else
return NO;// outside
}
在您的情况下,您可以在以下方法中将 imagView.center 作为点并将另一个 imageView.frame 作为矩形传递:
您还可以在以下 UITouch 方法中使用此方法:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
}
我开始学习使用Swift编程,并尝试解决这个问题,以下是我在Swift的playground上得出的结果:
// Code
var x = 1
var y = 2
var lowX = 1
var lowY = 1
var highX = 3
var highY = 3
if (x, y) >= (lowX, lowY) && (x, y) <= (highX, highY ) {
print("inside")
} else {
print("not inside")
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
CGRect rect1 = CGRectMake(vwTable.frame.origin.x,
vwTable.frame.origin.y, vwTable.frame.size.width,
vwTable.frame.size.height);
if (CGRectContainsPoint(rect1,touchLocation))
NSLog(@"Inside");
else
NSLog(@"Outside");
}