一、使用Surface对象
加载图片用pygame.image.load,返回一个Surface对象。事实上,屏幕也只是一个surface对象,pygame.display.set_mode返回一个屏幕的surface对象。
二、创建Surface对象
除了上面说的pygame.image.load外,还可以指定尺寸创建一个空的surface。
a = pygame.Surface((256,256))
这个Surface对象是全黑的。除了大小外,Surface函数还有flags和depth两个参数。
HWSURFACE | creates the image in video memory |
SRCALPHA | the pixel format will include a per-pixel alpha。创建有Alpha通道的surface,选择这个选项需要depth为32。 |
alpha_surface = pygame.Surface((256,256), flags=SRCALPHA, depth=32)
三、转换Surfaces
convert() | Creates a new copy of the Surface with the pixel format changed. 当一个surface多次使用blit时,最好使用convert。转换后的surface没有alpha。 |
convert_alpha() | change the pixel format of an image including per pixel alphas. |
四、矩形对象(Rectangle Objects)
pygame中有Rect类,用来存储和处理矩形对象(包含在pygame.locals)中。
Rect(left, top, width, height) |
Rect((left, top), (width, height)) |
有了Rect对象之后,可以对其做很多操作,例如调整大小、位置,判断一个点是否在其中等。
五、剪裁(Clipping)
surface中有裁剪区域(clip area),是一个矩形,定义了哪部分会被绘制,即若定义了这个区域,只有这个区域内的像素会被修改。
set_clip(screen_rect=None) |
设定区域,当参数为None时,重置。一个surface对象默认的剪裁区域为这个surface。 |
get_clip() | 得到剪裁区域,返回一个Rect对象。 |
六、子表面(Subsurfaces)
Subsurfaces是在一个surface中再提取出一个surface。当在subsurface上操作时,同时也向父表面上操作。这可以用来绘制图形文字,比如吧文字变成多种颜色。把整张图读入后,用subsurface将每个字分隔开。
my_font_image = Pygame.load("font.png")
letters = []
letters["a"] = my_font_image.subsurface((0,0), (80,80))
letters["b"] = my_font_image.subsurface((80,0), (80,80))
七、填充Surface
fill(color, rect=None, special_flags=0)
当rect参数为默认参数时,整个surface都会被填充。color参数可以为RGB或者RGBA。如果使用RGBA,除非surface有alpha通道(使用了SRCALPHA flag),否则RGBA的Alpha会被忽略。
八、设置Surface的像素
set_at((x, y), Color) : |
设置单个像素的颜色 |
get_at((x, y)) | 得到单个像素的颜色 |
九、锁定Surface
当对像素进行读或写操作时,surface会被锁定。一个锁定的surface,经常不能被显示或被pygame操作,所以除非必要,在手动lock之后不要忘了unlock。
所有pygame的函数如过需要锁定和解锁,这些操作时自动发生的。如果不想发生自动的lock和unlock(有些时候为了提高效率),可以在一些会造成自动锁定和解锁的语句前后注释掉这两句。
import pygame
from pygame.locals import *
from sys import exit
from random import randint
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
rand_col = (randint(0, 255), randint(0, 255), randint(0, 255))
# screen.lock)()
for _ in range(100):
rand_pos = (randint(0, 639), randint(0, 479))
screen.set_at(rand_pos, rand_col)
# screen.unlock()
pygame.display.update()
十、blit
blit(source, dest, area=None, special_flags = 0)
将源图像画到目标位置,dest可以为一个点,也可以是一个矩形,但只有矩形的左上角会被使用,矩形的大小不会造成影响。
area参数可以指定源图像中的一部分被画到目标位置。