python笔记(三十八) pygame(5) 改变透明度
import pygame
import sys
# 初始化pygame
pygame.init()
size = width ,height = 900, 500
bg = (255,255,255)
clock = pygame.time.Clock()
# 创建指定大小的窗口
screen = pygame.display.set_mode(size)
# 设置窗口标题
pygame.display.set_caption("闲得发慌")
# 加载图片 将所有图片格式转换成一样的 用convert
people = pygame.image.load("p.png").convert_alpha() #对于有alpha通道的png格式转换要加alpha
background = pygame.image.load("b.JPG").convert()
# 获得图像矩形位置
position = people.get_rect()
position.center = width // 2, height // 2
def blit_alpha(target,source,location,opacity):
x = location[0]
y = location[1]
temp = pygame.Surface((source.get_width(),source.get_height())).convert()
temp.blit(target,(-x,-y))
temp.blit(source,(0,0))
temp.set_alpha(opacity)
target.blit(temp,location)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(background,(0,0)) # (0,0)是背景位置
blit_alpha(screen,people,position,200)
# 更新界面
pygame.display.flip()
# 控制帧率
clock.tick(30)
由于png格式的图片自带alpha通道,所以不能使用set_alpha函数
所以我们自己写一个
首先利用temp = pygame.Surface((source.get_width(),source.get_height())).convert()把要变透明的部分弄成不带alpha通道的
x ,y是people的位置
-x,-y是他在背景的那块位置
首先将那块的背景贴上去,再将不带通道的people贴上去
最后改变透明度
