小甲鱼python083pygame笔记
小甲鱼所写blit_alpha()详解
带alpha通道的图像格式不能调用set_alpha()来整体变化透明度,但可以将其用bilt()方法贴在一个convert()返回的不带alpha通道的对象上,然后整体用set_alpha()以此巧妙绕过
原图是一张背景加乌龟
小乌龟的图片png格式并且除了小乌龟其它已经扣透明了
这里其实是用小乌龟的长宽新建了一个suface对象temp,可以想象成一个矩形框
然后先画上背景(相对于temp上-x,-y的地方),这样矩形框的背景(相对位置)就和效果图的背景一模一样了
然后再在位置上画上边框透明的小乌龟
然后把这个矩形框的temp整体调透明
然后把temp贴回已经画好background的screen上
import pygame
import sys
from pygame.locals import *
# 初始化Pygame
pygame.init()
size = width, height = 1000, 800
bg = (0, 0, 0) # RGB
clock = pygame.time.Clock()
# 创建指定大小的窗口 Surface
screen = pygame.display.set_mode(size)
# 设置窗口标题
pygame.display.set_caption("FishC Demo")
# 加载图片
turtle = pygame.image.load("turtle.png").convert_alpha()
background = pygame.image.load("1.gif").convert()
# 获得图像的位置矩形
position = turtle.get_rect()
position.center = 180, 120
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)) # 虽然和原图同步画上背景的(-x,-y是相对于temp而言
# 背景screen左上角位置,这样保持位置矩形的背景和原画位置同步),
# 但temp是一个位置矩形,后续使用时大小和位置不变
temp.blit(source, (0, 0)) # 在temp矩形画上乌龟
temp.set_alpha(opacity) # 设置透明度
target.blit(temp, location) # 把temp位置矩形的图画画到target(背景原图)同一位置矩形上
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(background, (0, 0))
blit_alpha(screen, turtle, position, 200)
# screen.blit(turtle, position)
# 更新界面
pygame.display.flip()
# 30帧/s
clock.tick(30)