四边形的排序坐标

Sort coordinates of quad polygon

我正在尝试对四边形的坐标进行排序。

多边形大致是一个矩形,但它不是一个完美的矩形。

示例如下:

我从这个多边形得到的只是一组 4 个坐标,每次收到它时我都想按顺时针方向对其进行排序。第一个点必须始终在左上角。

知道如何解决这个问题吗?

再次回答我自己的问题。假设我们有一个四边形的点数组。原点 (0,0) 最多位于左上角。顺序是任意的。在这里我简单说一下。

NSMutableArray *pointsArray = [[NSMutableArray alloc] initWithObjects:
                                 [NSValue valueWithCGPoint:rf.bottomLeft],
                                 [NSValue valueWithCGPoint:rf.topRight],
                                 [NSValue valueWithCGPoint:rf.topLeft],
                                 [NSValue valueWithCGPoint:rf.bottomRight],
                                 nil];

首先,我们按x坐标从小到大对点进行排序。

    NSArray *sortedByX = [pointsArray sortedArrayUsingComparator:^NSComparisonResult(NSValue *obj1, NSValue *obj2) {
        CGPoint p1 = [obj1 CGPointValue];
        CGPoint p2 = [obj2 CGPointValue];
        return p1.x > p2.x;
    }];

然后我们得到前2个点(这两个基本上是左上角和左下角)。所以我们检查这两个的 Y 值以确定哪个在顶部,哪个在底部,我们可以立即分配。

    CGPoint Pt1, Pt2, Pt3, Pt4;

    CGPoint ptMinX1 = [[sortedByX objectAtIndex:0] CGPointValue];
    CGPoint ptMinX2 = [[sortedByX objectAtIndex:1] CGPointValue];

    if (ptMinX1.y<ptMinX2.y) {
        Pt1 = ptMinX1;
        Pt4 = ptMinX2;
    } else {
        Pt1 = ptMinX2;
        Pt4 = ptMinX1;
    }

确定右侧点也是如此。

    CGPoint ptMaxX1 = [[sortedByX objectAtIndex:2] CGPointValue];
    CGPoint ptMaxX2 = [[sortedByX objectAtIndex:3] CGPointValue];

    if (ptMaxX1.y<ptMaxX2.y) {
        Pt2 = ptMaxX1;
        Pt3 = ptMaxX2;
    } else {
        Pt3 = ptMaxX1;
        Pt2 = ptMaxX2;
    }

最后我们按顺时针顺序得到积分:

// Pt1   Pt2
//
// Pt4   Pt3

然后您可以随意排列这些点(逆时针、之字形或其他)