如何判断一个点是不是在方框(CGRect)、圆(Circle)、三角形(Triangle)内呢?
1.方框
//苹果官方方法可以判断+ (BOOL)point:(CGPoint)point inSquareArea:(CGRect)rect { return CGRectContainsPoint(rect, point); }
2.圆
//圆心到点的距离>?半径+ (BOOL)point:(CGPoint)point inCircleRect:(CGRect)rect { CGFloat radius = rect.size.width/2.0; CGPoint center = CGPointMake(rect.origin.x + radius, rect.origin.y + radius); double dx = fabs(point.x - center.x); double dy = fabs(point.y - center.y); double dis = hypot(dx, dy); return dis <= radius; }
3.三角形
//点都否在三边线的右边?这个应该不是最优解+ (BOOL)point:(CGPoint)point inTriangleVertexPointsArea:(NSArray<NSValue *> *)vertexPoints { if (vertexPoints.count == 3) { CGPoint point0 = [vertexPoints[0] CGPointValue]; CGPoint point1 = [vertexPoints[1] CGPointValue]; CGPoint point2 = [vertexPoints[2] CGPointValue]; BOOL b0 = [self sign:point point1:point0 point2:point1] < 0.0f; BOOL b1 = [self sign:point point1:point1 point2:point2] < 0.0f; BOOL b2 = [self sign:point point1:point2 point2:point0] < 0.0f; return ((b0 == b1) && (b1 == b2)); } return NO; } + (CGFloat)sign:(CGPoint)point0 point1:(CGPoint)point1 point2:(CGPoint)point2 { return (point0.x - point2.x) * (point1.y - point2.y) - (point1.x - point2.x) * (point0.y - point2.y); }
作者:紧张的牛排
链接:https://www.jianshu.com/p/50382cd74f92