简体   繁体   English

如何在pygame中绘制透明图像?

[英]How to draw a transparent image in pygame?

Consider a chess board, i have a transparent image of queen(queen.png) of size 70x70 and i want to display it over a black rectangle. 考虑一个棋盘,我有一个大小为70x70的皇后(queen.png)的透明图像,我想在黑色矩形上显示它。 Code: 码:

BLACK=(0,0,0)
queen = pygame.image.load('queen.png')

pygame.draw.rect(DISPLAYSURF, BLACK, (10, 10, 70, 70))
DISPLAYSURF.blit(queen, (10, 10))

Error: i am not getting transparent image ie black rectangle is not visible at all, only queen with white background. 错误:我没有获得透明图像,即根本看不到黑色矩形,只有白色背景的女王。 Please suggest 请建议

尝试更改在女王中加载的行:

queen = pygame.image.load('queen.png').convert_alpha()

I don't think pygame.draw.rect supports alpha channels. 我不认为pygame.draw.rect支持alpha通道。 You should use pygame.Surface 你应该使用pygame.Surface

queen = pygame.Surface([10, 10], pygame.SRCALPHA, 32)

When you call the pygame.image.load() method, Pygame reads an image file from your hard drive and returns a surface object containing the image data. 当你调用pygame.image.load()方法时,Pygame从你的硬盘驱动器中读取一个图像文件并返回一个包含图像数据的表面对象。 This surface instance is the same type of object as your display surface, but it represents an image stored in memory. 此曲面实例与显示曲面的对象类型相同,但它表示存储在内存中的图像。

By calling the convert() method of an (image-) surface instance with no arguments passed, Pygame converts the image surface to the same format as your main display surface. 通过调用没有传递参数的(image-)曲面实例的convert()方法,Pygame将图像曲面转换为与主显示曲面相同的格式。 This is recommended, because it is faster to draw or blit images which have the same pixel format (depth, flags etc.) as the display surface. 建议这样做,因为绘制或blit图像具有与显示表面相同的像素格式(深度,标记等)更快。 When you use this method, the converted surface will have no alpha information . 使用此方法时,转换后的曲面将没有alpha信息

Fortunately Pygame surface objects provide also a convert_alpha() method, which converts an (image-) surface to a fast format that preserves any alpha information . 幸运的是,Pygame表面对象还提供了convert_alpha()方法,该方法将(图像)表面转换为保留任何alpha信息的快速格式。

This means you need to call the convert_alpha() method of your queen instance for preserving any alpha information of the original image: 这意味着您需要调用queen实例的convert_alpha()方法来保留原始图像的任何alpha信息:

BLACK=(0,0,0)

#load the image and convert the returned surface using the convert_alpha() method
queen = pygame.image.load('queen.png').convert_alpha() 

pygame.draw.rect(DISPLAYSURF, BLACK, (10, 10, 70, 70))
DISPLAYSURF.blit(queen, (10, 10))
pygame.display.update()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM