这确实是一个艰难的过程。我玩了很多 QPolygon 的几种方法,如 intersected、united、subtracted,但没有一个成功。
例如,我认为这可能有效:复制多边形,将点添加到副本中,然后检查结果是否为空。如果该点位于多边形的周长上,则原件和副本都应具有相同的形状,因此结果应为空。
def on_perimeter(poly, point):
poly2 = poly + QtGui.QPolygon() # copy the polygon
poly2.add(point)
return poly.subtracted(poly2).isEmpty()
但是,多边形似乎是按照给定点的顺序“绘制”的,因此,如果您只是添加点,这会导致其他形状。例如,考虑形成正方形的点(0,0) (0,2) (2.2) (2,0),您要检查(0,1)。然后,如果您只是在末尾添加点,这将“连接”(2,0) 与(0,1) 和(0,1) 与(0,0),因为多边形必须是封闭形式。这给出了一些其他形状。因此你会有在正确的位置插入点以获得相同的形状。对于这个例子,它就在(0,0)之后。所以我想,好吧,让我们尝试上面所有可能的排列,只有一种配置(及其由旋转和反转产生的变换),使得减法的结果为空。
import itertools
def on_perimeter(poly, point):
points = [point] # the points of the new polygon
for ii in range(0, poly.size()):
points += [poly.point(ii)]
permuts = list(itertools.permutations(points)) # all possible permutations
checks = 0
for permut in permuts:
checks += int(poly.subtracted(QtGui.QPolygon(list(permut))).isEmpty())
return checks
但不知何故,这也不起作用。尝试您的示例,我得到QP(4,5) 和QP(3,2) 的checks = 10 值QP(1,1) checks = 20 和QP(1,3) checks = 0。我所期望的是获得所有点的checks = 12(因为它们都位于外围)。 12 因为poly2 是由6 点组成的,所以您可以旋转 点6 次,并在您颠倒顺序 之后执行相同操作,所以@ 987654346@ 包含在permuts 中的不同配置导致相同的形状。此外,如果以相反的方式执行减法(即QtGui.QPolygon(list(permut)).subtracted(poly).isEmpty()),我会为每个点得到True,对于甚至不在多边形内但在外的点。
我在上述函数中使用united 和intersected 而不是isEmpty 尝试了类似的事情:
tmp = QtGui.QPolygon(list(permut))
checks += int(poly.intersected(tmp) == poly.united(tmp))
这里也一样,如果该点实际上位于周界上,它应该只评估为True。但这几乎可以让False 回馈给我检查您上述示例的每一点。
我没有看QPolygon 方法的源代码(如果有的话),但似乎发生了一些奇怪的事情。
所以我建议你编写一个自己的方法来评估多边形中的所有线(如果点位于其中之一上)。
def on_perimeter(poly, point):
lines = []
for ii in range(1, poly.size()):
p1 = poly.point(ii-1)
p2 = poly.point(ii)
lines += [ ( (p1.x(), p1.y()), (p2.x(), p2.y()) ) ]
lines += [ ( (poly.last.x(), poly.last.y()), (poly.first.x(), poly.first.y()) ) ]
for line in lines:
dx = line[1][0] - line[0][0]
dy = line[1][1] - line[0][1]
if abs(dx) > abs(dy) and dx*dy != 0 or dx == 0 and dy == 0: # abs(slope) < 1 and != 0 thus no point with integer coordinates can lie on this line
continue
if dx == 0:
if point.x() == line[0][0] and (point.y()-line[[0][1])*abs(dy)/dy > 0 and (line[1][1]-point.y())*abs(dy)/dy > 0:
return True
if dy == 0:
if point.y() == line[0][1] and (point.x()-line[[0][0])*abs(dx)/dx > 0 and (line[1][0]-point.x())*abs(dx)/dx > 0:
return True
dx2 = point.x() - line[0][0]
dy2 = point.y() - line[0][1]
if dx*dx2 < 0 or dy*dy2 < 0:
continue
if abs(dx) % abs(dx2) == 0 and abs(dy) % abs(dy2) == 0:
return True
return False
这似乎有点繁重,但重要的是只使用整数执行所有计算,因为浮点精度可能会导致错误的结果(QPolygon 无论如何都只接受整数点)。虽然尚未测试,但它应该可以工作。