PyGame图形绘制函数详解

文章目录

五种图形

除了直线之外,pygame中提供了多种图形绘制函数,除了必要的绘图窗口、颜色以及放在最后的线条宽度之外,它们的参数如下表所示

函数 图形 参数/类型
rect 矩形 Rect
ellipse 椭圆 Rect
arc 椭圆弧 Rect, st, ed
circle 圆形 center, radius
polygon 多边形 points

从参数类别可以看出,矩形和椭圆的绘图逻辑是一致的,可以理解为,用矩形约束创造的椭圆,即矩形的内切椭圆;而椭圆弧也无非是多了个起止角度而已。

圆形和多边形则不然,前者通过圆心和半径,后者则根据一组点集。下面集中展示一下这几种绘图函数的基本用法。

import pygame
from pygame.draw import *

pygame.init()
screen = pygame.display.set_mode((640, 360))

pts = [(400, 0), (450, 100), (500, 0), (600, 100),
       (620, 300), (450, 350)]
while True:
    if pygame.QUIT in [e.type for e in pygame.event.get()]:
        pygame.quit()
        break
    screen.fill("purple")
    rect(screen, "green", pygame.Rect(10, 30, 100, 300))
    ellipse(screen, "red", pygame.Rect(120, 30, 100, 300))
    arc(screen, "black", pygame.Rect(230, 30, 100, 300), 0, 4.5)
    circle(screen, "blue", pygame.Vector2(360, 180), 40)
    polygon(screen, "pink", pts)
    pygame.display.flip()

效果如下

在这里插入图片描述

矩形

矩形在pygame中是非常基础的图形,使用场景也非常多,其优势在于,可以非常便捷地判断两个物体是否发生了碰撞。其完整的参数列表如下

rect(surface, color, rect, width=0, border_radius=0, border_top_left_radius=-1, border_top_right_radius=-1, border_bottom_left_radius=-1, border_bottom_right_radius=-1)

其中,额外出现的5个以radius结尾的参数,可用于设置矩形的圆角。示例如下

pygame.init()
screen = pygame.display.set_mode((640, 360))
while True:
    if pygame.QUIT in [e.type for e in pygame.event.get()]:
        pygame.quit()
        break
    screen.fill("purple")
    rect(screen, "green", pygame.Rect(50, 30, 200, 300), border_radius=10)
    rect(screen, "red", pygame.Rect(280, 30, 300, 300),
    border_top_left_radius=10, border_top_right_radius=40, border_bottom_left_radius=80, border_bottom_right_radius=160)
    pygame.display.flip()

效果如下

在这里插入图片描述

圆形

圆形与矩形相似,除了基础的绘图参数外,也提供了4个可定制的参数。

circle(surface, color, center, radius, width=0, draw_top_right=None, draw_top_left=None, draw_bottom_left=None, draw_bottom_right=None)

这四个参数均为布尔类型,用于控制圆形的四个角,若均不指定,则无影响。若指定其中某个参数为True,则将只绘制这个方向的四分之一圆弧,示例如下

pygame.init()
screen = pygame.display.set_mode((640, 360))
while True:
    if pygame.QUIT in [e.type for e in pygame.event.get()]:
        pygame.quit()
        break
    screen.fill("purple")
    circle(screen, (1, 136, 225), pygame.Vector2(320, 180), 150,
        draw_top_left=True, draw_bottom_right=True)
    circle(screen, "white", pygame.Vector2(320, 180), 150,
        draw_top_right=True, draw_bottom_left=True)
    pygame.display.flip()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_37816922/article/details/134924108