就是填充一个区域
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
def lines(point1,point2,List):
dx = point2[0] - point1[0]
dy = point2[1] - point1[1]
maxxy = max(abs(dx),abs(dy))
stepx = dx / maxxy #步长
stepy = dy / maxxy
for i in range(maxxy + 1):
x = point1[0] + stepx * i
y = point1[1] + stepy * i
ix = sswr(x)
iy = sswr(y)
List[ix-1][iy-1] = 1
def sswr(x): #四舍五入
if x >= 0:
return int(x+0.5)
else:
return int(x-0.5)
def Fill4(x,y,List):
m,n = len(List),len(List[0])
if x <= n and x >= 0 and y <= m and y >= 0:
if List[x][y] == 0:
List[x][y] = 2
Fill4(x+1,y,List)
Fill4(x,y+1,List)
Fill4(x-1,y,List)
Fill4(x,y-1,List)
def Fill8(x,y,List):
m,n = len(List),len(List[0])
if x < n and x >= 0 and y < m and y >= 0:
if List[x][y] == 0:
List[x][y] = 2
Fill8(x+1,y,List)
Fill8(x,y+1,List)
Fill8(x-1,y,List)
Fill8(x,y-1,List)
Fill8(x+1,y+1,List)
Fill8(x-1,y+1,List)
Fill8(x-1,y-1,List)
Fill8(x+1,y-1,List)
def draw(List):
m,n = len(List),len(List[0])
for i in range(m):
for j in range(n):
if List[i][j] == 1:
glColor3f(0.0,0.0,0.0)
glVertex2i(j, i)
if List[i][j] == 2:
glColor3f(1.0,1.0,0.0)
glVertex2i(j, i)
def Display():
glPointSize(30)
glBegin(GL_POINTS)
m,n = 20,20
PointList = [[4,19],[18,3],[1,2]]
List = [[0 for i in range(n+1)] for j in range(m+1)]
p1 = PointList[-1]
for i in PointList:
p2 = i
lines(p1,p2,List)
p1 = p2
Fill8(4,5,List)
draw(List)
glEnd()
glFlush()
def main():
glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)
glutInitWindowSize(600,600)
glutCreateWindow("window")
gluOrtho2D(0,20,0,20)
glClearColor(0.5,0.5,0.5,0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glutDisplayFunc(Display)
glutMainLoop()
main()
运行结果
显然,对于8连通是失败的,这种斜对角的会漏出去,代码中使用4连通填充就没事了4-Fill