iOS - 如何判断一个点是不是在方框(CGRect)、圆(Circle)、三角形(Triangle)内呢?

笑着哭i 提交于 2020-02-13 23:21:11

如何判断一个点是不是在方框(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);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!