如何使用SRCALPHA模式在pygame中将alpha设置为canvas?

时间:2017-04-22 16:48:55

标签: python image-processing pygame pygame-surface

我上课来操纵图像,有表面"在SRCALPHA模式下具有pygame表面的变量。如何设置额外的alpha?。

我的代码是:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import Image
import os 

class ImageManipulation:

    def loadPicture(self, imagePath):
        # http://stackoverflow.com/questions/38665920/convert-pil-image-into-pygame-surface-image
        # http://stackoverflow.com/questions/29662908/how-do-i-blit-an-image-to-a-surface-in-pygame-thats-the-same-size-as-a-rectangl
        # http://stackoverflow.com/questions/28005641/how-to-add-a-background-image-into-pygame

        image    = Image.open(imagePath)
        mode     = image.mode
        size     = image.size
        data     = image.tobytes()
        py_image = pygame.image.fromstring(data, size, mode)

        self.width = py_image.get_rect()[2]
        self.height = py_image.get_rect()[3]

        surface = pygame.Surface((self.width, self.height), pygame.SRCALPHA, 32)
        surface = surface.convert_alpha()
        surface.blit(py_image, py_image.get_rect())

        self.surface = surface

    def setAlpha(self, opacity):
        # howto made this?

使用self.set_alpha(opacity)不起作用时,使用transform()函数混合图层时会产生填充背景但不保留透明背景。

我已经加载了一个带有完全透明部分的按钮,需要将50%的不透明度设置为所有按钮并保留背景透明度。示例:http://www.clipartbest.com/cliparts/eTM/y5L/eTMy5LzAc.png

1 个答案:

答案 0 :(得分:0)

我找到了使用特殊标志的解决方案:

def styleSetAlpha(self, opacity):
    alpha_img = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
    alpha_img.fill((255, 255, 255, opacity))
    self.surface.blit(alpha_img, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)

来源:PyGame: translucent sprites with per pixel alpha