IOS development-determine whether a point is in a region
IOS sometimes needs to determine whether to touch a certain image area. That is, whether the touch point is within the area of a graph.
There are many solutions. Here is a simple introduction.
We can create an area using CGPath. The area is the area where the line segments between two points are closed and merged. Then, we can use CGPath's function CGPathContainsPoint to determine whether the point is in the area.
For example, a simple rectangle is created here. Its frame is (4, 4, 10, 10 ). The coordinates of the four vertices are (4, 4), (4, 14), (14, 14), (14, 4)
Obviously, (1, 1) is not in this region (5, 5.
The Code is as follows:
- (void)viewDidLoad { [super viewDidLoad]; CGMutablePathRef pathRef=CGPathCreateMutable(); CGPathMoveToPoint(pathRef, NULL, 4, 4); CGPathAddLineToPoint(pathRef, NULL, 4, 14); CGPathAddLineToPoint(pathRef, NULL, 14, 14); CGPathAddLineToPoint(pathRef, NULL, 14, 4); CGPathAddLineToPoint(pathRef, NULL, 4, 4); CGPathCloseSubpath(pathRef); CGPoint point=CGPointMake(5, 5); CGPoint outPoint=CGPointMake(1, 1); if (CGPathContainsPoint(pathRef, NULL, point, NO)) { NSLog(@"point in path!"); } if (!CGPathContainsPoint(pathRef, NULL, outPoint, NO)) { NSLog(@"outPoint out path!"); }}