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)

 

 

 

 

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)

 

 

 

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)

 


 

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)

 

 

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)

 

 

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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM