最近很火一些简单图形构成的小游戏,这里介绍一些绘制图形的函数。

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)绘制基本图形_抗锯齿_02

 

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)绘制基本图形_抗锯齿_03

 

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)绘制基本图形_抗锯齿_04

 

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)绘制基本图形_填充矩形_05

 

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)绘制基本图形_sed_06

 


作者:王陸