如何使用Alpha通道为png图像着色?

时间:2019-02-11 15:22:13

标签: python pygame

我正在尝试编码典型的DVD弹跳屏保。我对此感到满意,但是我想在每次碰到徽标时更改徽标的颜色。我使用了fill(),但是徽标更改为彩色矩形。我要更改徽标的颜色,同时注意图像的Alpha通道。

from pygame import *
import random

#set canvas size variables
width = 700
height = 450

#draw canvas
screen = display.set_mode((width,height))
display.set_caption('Graphics')

#initial XY coordinates where game starts
x = random.randint(1, width)
y = random.randint(1, height)

#import logo
logo_img = image.load('dvd_logo_alpha.png')

R = 255
G = 255
B = 255

def logo(x,y):
    screen.blit(logo_img, (x,y))

def Col():
    R = random.randint(100,255)
    G = random.randint(100,255)
    B = random.randint(100,255)

#speed of the logo
dx = 3
dy = 3

endProgram = False

while not endProgram:
    for e in event.get():
        if e.type == QUIT:
            endProgram = True

    #speed changes position XY
    x += dx
    y += dy

    #detection of collision with border of screen
    if y<0 or y>height-47:
        dy *= -1
        R = random.randint(100,255)
        G = random.randint(100,255)
        B = random.randint(100,255)
    if x<0 or x>width-100:
        dx *= -1
        R = random.randint(100,255)
        G = random.randint(100,255)
        B = random.randint(100,255)

    screen.fill((0))
    logo_img.fill((R,G,B)) #here is the problem I can not solve
    logo(x,y)
    display.update()

1 个答案:

答案 0 :(得分:1)

首先,您必须创建一个具有Alpha通道的图像,以使png图像的透明区域不可见。使用pygame.Surface.convert_alpha()创建具有Alpha通道的曲面:

tintImage = image.convert_alpha()

要用pygame.Surface.fill()着色图像,special_flags也已设置为BLEND_RGBA_MULT。这导致图像的所有像素乘以颜色,而不是颜色:

tintImage.fill((R, G, B, 255), None, BLEND_RGBA_MULT)

请注意,由于必须使用不同的颜色对图像进行着色,因此必须保留原始图像。使用功能logo复制图像,然后“着色”图像的副本“ blit”:

def logo(x, y, color):
    tintImage = logo_img.convert_alpha()
    tintImage.fill((R, G, B, 255), None, BLEND_RGBA_MULT)
    screen.blit(tintImage, (x, y))

在程序的主循环中调用该函数:

endProgram = False
while not endProgram:
    for e in event.get():
        if e.type == QUIT:
            endProgram = True

    #speed changes position XY
    x += dx
    y += dy

    #detection of collision with border of screen
    if y<0 or y>height-47:
        dy *= -1
        R = random.randint(100,255)
        G = random.randint(100,255)
        B = random.randint(100,255)
    if x<0 or x>width-100:
        dx *= -1
        R = random.randint(100,255)
        G = random.randint(100,255)
        B = random.randint(100,255)

    screen.fill((0))

    #logo_img.fill((R,G,B)) #here is the problem I can not solve
    logo(x, y, (R, G, B))

    display.update()