iOS: verify if a point is inside a rect
Is there a way to verify if a CGPoint
is inside a specific CGRect
?
An example would be:
I'm dragging a UIImageView
and I want to verify if its central point CGPoint
is inside another UIImageView
.
Swift 4
let view = ...
let point = ...
view.bounds.contains(point)
Objective-C
Use CGRectContainsPoint()
:
bool CGRectContainsPoint(CGRect rect, CGPoint point);
Parameters
-
rect
The rectangle to examine. -
point
The point to examine. Return Value true if the rectangle is not null or empty and the point is located within the rectangle; otherwise, false.
A point is considered inside the rectangle if its coordinates lie inside the rectangle or on the minimum X or minimum Y edge.
In Swift that would look like this:
let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = CGRectContainsPoint(someFrame, point)
Swift 3 version:
let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = someFrame.contains(point)
Link to documentation . Please remember to check containment if both are in the same coordinate system if not then conversions are required (some example)
In swift you can do it like this:
let isPointInFrame = frame.contains(point)
"frame" is a CGRect and "point" is a CGPoint
UIView's pointInside:withEvent: could be a good solution. Will return a boolean value indicating wether or not the given CGPoint is in the UIView instance you are using. Example:
UIView *aView = [UIView alloc]initWithFrame:CGRectMake(0,0,100,100);
CGPoint aPoint = CGPointMake(5,5);
BOOL isPointInsideView = [aView pointInside:aPoint withEvent:nil];