天天看點

Python Pygame(5)繪制基本圖形

最近很火一些簡單圖形構成的小遊戲,這裡介紹一些繪制圖形的函數。

1.繪制矩形

rect(Surface,color,Rect,width=0)      

第一個參數指定矩形繪制到哪個Surface對象上

第二個參數指定顔色

第三個參數指定矩形的範圍(left,top,width,height)

第四個參數指定矩形邊框的大小(0表示填充矩形)

例如繪制三個矩形:

pygame.draw.rect(screen, BLACK, (50, 50, 150, 50), 0)
    pygame.draw.rect(screen, BLACK, (250, 50, 150, 50), 1)
    pygame.draw.rect(screen, BLACK, (450, 50, 150, 50), 10)      
Python Pygame(5)繪制基本圖形

2.繪制多邊形

polygon(Surface,color,pointlist,width=0)      

polygon()方法和rect()方法類似,除了第三參數不同,polygon()方法的第三個參數接受的是多邊形各個頂點坐标組成的清單。

例如繪制一個多邊形的魚

points = [(200, 75), (300, 25), (400, 75), (450, 25), (450, 125), (400, 75), (300, 125)]
pygame.draw.polygon(screen, GREEN, points, 0)      
Python Pygame(5)繪制基本圖形

3.繪制圓形

circle(Surface,color,pos,radius,width=0)      

其中第一、二、五個參數根前面的兩個方法是一樣的,第三參數指定圓形位置,第四個參數指定半徑的大小。

例如繪制一個同心圓:

pygame.draw.circle(screen, RED, position, 25, 1)
    pygame.draw.circle(screen, GREEN, position, 75, 1)
    pygame.draw.circle(screen, BLUE, position, 125, 1)      
Python Pygame(5)繪制基本圖形

4.繪制橢圓形

ellipse(Surface,color,Rect,width=0)      

橢圓利用第三個參數指定的矩形來繪制,其實就是将所需的橢圓限定在設定好的矩形中。

pygame.draw.ellipse(screen, BLACK, (100, 100, 440, 100), 1)
    pygame.draw.ellipse(screen, BLACK, (220, 50, 200, 200), 1)      
Python Pygame(5)繪制基本圖形

5.繪制弧線

arc(Surface,color,Rect,start_angle,stop_angle,width=1)      

這裡Rect也是用來限制弧線的矩形,而start_angle和stop_angle用于設定弧線的起始角度和結束角度,機關是弧度,同時這裡需要數學上的pi。

pygame.draw.arc(screen, BLACK, (100, 100, 440, 100), 0, math.pi, 1)
pygame.draw.arc(screen, BLACK, (220, 50, 200, 200), math.pi, math.pi * 2, 1)      
Python Pygame(5)繪制基本圖形

6.繪制線段

line(Surface,color,start_pos,end_pos,width=1)
lines(Surface,color,closed,pointlist,width=1)      

line()用于繪制一條線段,而lines()用于繪制多條線段。

其中lines()的closed參數是設定是否首尾相接。

這裡在介紹繪制抗鋸齒線段的方法,aaline()和aalines()其中aa就是antialiased,抗鋸齒的意思。

aaline(Surface,color,startpos,endpos,blend=1)
aalines(Surface,color,closed,pointlist,blend=1)      

最後一個參數blend指定是否通過繪制混合背景的陰影來實作抗鋸齒功能。由于沒有width方法,是以它們隻能繪制一個像素的線段。

points = [(200, 75), (300, 25), (400, 75), (450, 25), (450, 125), (400, 75), (300, 125)]
    pygame.draw.lines(screen, GREEN, 1, points, 1)
    pygame.draw.line(screen, BLACK, (100, 200), (540, 250), 1)
    pygame.draw.aaline(screen, BLACK, (100, 250), (540, 300), 1)
    pygame.draw.aaline(screen, BLACK, (100, 300), (540, 350), 0)      
Python Pygame(5)繪制基本圖形

作者:王陸