@yanglt7
2018-12-11T15:56:28.000000Z
字数 2454
阅读 797
Pygame
绘制矩形的语句格式如下:
rect(Surface, color, Rect, width=0)
rect() 方法用于在 Surface 对象上边绘制一个矩形。
例 8-1
关于最后一个参数 width。
...
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
...
screen.fill(WHITE)
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) # 边框向外扩展
...
clock.tick(10)
边框是向外延伸的。
绘制多边形的语句如下:
polygon(Surface, color, pointlist, width=0)
polygon() 的用法跟 rect() 类似,除了第三个参数不同,polygon() 方法的第三个参数接受由多边形各个顶点坐标组成的列表。
例 8-2
...
points = [(200, 75), (300, 25), (400, 75), (450, 25), (450, 125), (400, 75), (300, 125) ]
...
pygame.draw.polygon(screen, GREEN, points, 0)
...
绘制圆形的语句格式如下:
circle(Surface, color, pos, radius, width=0)
第一、二、五个参数跟前面的两个方法一样,第三个参数指定圆心的位置,第四个参数指定半径的大小。
例 8-3
...
position = size[0] // 2, size[1] // 2
moving = False
...
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
moving = True
if event.type == MOUSEBUTTONUP:
if event.button == 1:
moving = False
if moving:
position = pygame.mouse.get_pos()
screen.fill(WHITE)
pygame.draw.circle(screen, GREEN, position, 25, 1)
pygame.draw.circle(screen, RED, position, 75, 1)
pygame.draw.circle(screen, BLUE, position, 125, 1)
...
绘制椭圆形的语句格式如下:
ellipse(Surface, color, Rect, width=0)
例 8-4
...
pygame.draw.ellipse(screen, BLACK, (100, 100, 440, 100), 1)
pygame.draw.ellipse(screen, BLACK, (220, 50, 200, 200), 1)
...
绘制弧线的语句格式如下:
arc(Surface, color, Rect, start_angle, stop_angle, width=1)
例 8-5
import math
...
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)
...
arc() 方法是绘制椭圆弧,也就绘制椭圆上的一部分弧线,因为弧线并不是全包围图形,所以不能将 width 设置为 0 进行填充。start_angle 和 stop_angle 参数用于设置弧线的起始角度和结束角度,单位是弧度。
绘制线段的语句格式如下:
line(Surface, color, start_pos, end_pos, width=1)
lines(Surface, color, closed, pointlist, width=1)
line() 用于绘制一条线段,而 lines() 则用于绘制多条线段。其中,lines() 方法的 closed 参数设置首尾是否相连,跟 polygon() 有点像,但区别是线段不能通过设置 width 参数为 0 进行填充。
aaline(Surface, color, startpos, endpos, blend=1)
aalines(Surface, color, closed, pointlist, blend=1)
aaline(), aalines() 方法是用来绘制抗锯齿的线段,aa 就是 antialiased,抗锯齿的意思。最后一个参数 blend 指定是否通过绘制混合背景的阴影来实现抗锯齿功能。由于没有 width 方法,所以它们只能绘制 1 个像素的线段。
例 8-6
...
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》