1. 程式人生 > 實用技巧 >Python 用大量小矩形來畫曲線

Python 用大量小矩形來畫曲線

 1 import sys, pygame, math
 2 
 3 pygame.init()
 4 screen = pygame.display.set_mode([640, 480])
 5 
 6 screen.fill([255, 255, 255])
 7 for x in range(0, 640):
 8     y = int(math.sin(x / 640.0 * 4 * math.pi) * 200 + 240)#y座標
 9     pygame.draw.rect(screen, [0, 0, 0], [x, y, 1, 1], 1)#小矩形來畫sinx
10 
11 pygame.display.flip()
12 running = True 13 while running: 14 for event in pygame.event.get(): 15 if event.type == pygame.QUIT: 16 running = False 17 pygame.quit()

如果線寬用0的話,什麼都不會顯示,因為這樣的小矩形沒有'中間部分' 來填充

可以看到,上面的圖是一個一個的點,點中間還存在空格,這是因為,在比較陡的地方,我們必須上移3個畫素而向右只移動一個畫素,而且我們畫的是點,不是線

下面是連線多個點的方法:

 1 import
sys, pygame, math 2 3 pygame.init() 4 screen = pygame.display.set_mode([640, 480]) 5 plotPoint = [] 6 7 screen.fill([255, 255, 255]) 8 for x in range(0, 640): 9 y = int(math.sin(x / 640.0 * 4 * math.pi) * 200 + 240)#y座標 10 plotPoint.append([x, y]) 11 12 pygame.draw.lines(screen, [0, 0, 0], False, plotPoint, 1)
13 '''這裡的五個引數作用: 14 第一:畫線的表面 15 第二:顏色 16 第三:是否要畫一條線將最後一個點與第一個點相連線,使形狀閉合。 17 我們不希望正弦曲線閉合,所以引數為False 18 第四:要連線的點的列表 19 第五:線寬 20 ''' 21 pygame.display.flip() 22 running = True 23 while running: 24 for event in pygame.event.get(): 25 if event.type == pygame.QUIT: 26 running = False 27 pygame.quit()