iOS - How to determine a point is not in the box (CGRect), circle (Circle), Triangle (Triangle) within it?

How to determine a point is not in the box (CGRect), circle (Circle), Triangle (Triangle) within it?

1. Box

//苹果官方方法可以判断
+ (BOOL)point:(CGPoint)point inSquareArea:(CGRect)rect {
    return CGRectContainsPoint(rect, point);
}

2. round

//圆心到点的距离>?半径
+ (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. Triangle

//点都否在三边线的右边?这个应该不是最优解
+ (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);
}
He published 188 original articles · won praise 19 · views 80000 +

Guess you like

Origin blog.csdn.net/songzhuo1991/article/details/104301180
Recommended