如何在pygame中动态生成半透明图像

2024-10-01 00:14:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我在pygame中开发自定义gui组件,在制作slider组件时,我给slider一个Draw(parentSurface)函数,该函数将滑块绘制到父曲面的存储位置。在

现在,这是可行的,但滑块存储两个图像:

  • 由平铺动态生成的幻灯片图像,以匹配滑块的给定长度,以给定长度的宽度和3个像素的高度进行测量;以及
  • “选择”图像,它只是一个小的8x12指示器,用于显示滑块的位置。在

问题是当我Draw(parentSurface)我这样做时:

def Draw(self, parsurf):
    '''draw the element on parsurf at the given location'''
    w1 = self.slider_img.get_width()
    h1 = self.slider_img.get_height()
    w2 = self.select_img.get_width()
    h2 = self.select_img.get_height()
    self.image = pygame.Surface((w1, h2 + h1))
    self.image = ColorMod.Transparency(self.image, 0)
    self.image.blit(self.slider_img, (0, self.image.get_height()-h1))
    x = self.value / self.conversionratio
    self.image.blit(self.select_img, (x- w2/2, 0))
    if self.debug_on:
        print "attempting to blit to the given surface"
    parsurf.blit(self.image, self.loc)

但是,它在self.image上以黑色背景闪烁。我希望它是半透明的,这样背景就可以通过self.image上什么也没有的地方显示出来。我应该放弃self.image并直接将self.slider_img和{}直接绘制到父曲面吗?在


Tags: the图像imageselfimggeth1select
2条回答

您必须通过调用self.image.set_alpha((0,0,0))使图像透明,也可以在^{中调用self.image = pygame.Surface((width, height), pygame.SRCALPHA),您需要将其更改为self.image = pygame.Surface((width, height), pygame.SRCALPHA) 我还建议去掉{}

如果self.slider_img名称所引用的Surface对象是动态创建的,那么当您第一次创建Surface实例时,您应该调用Surface.convert_alpha来获得一个Surface,该对象的每像素alpha值具有适当的像素格式。然后您应该能够根据需要逐像素地设置alpha。在

http://www.pygame.org/docs/ref/surface.html#pygame.Surface.convert_alpha

相关问题 更多 >