在pygame中绘制一个透明矩形 [英] Draw a transparent rectangle in pygame

查看:338
本文介绍了在pygame中绘制一个透明矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何绘制带有 alpha 颜色的矩形?我有:

How can I draw a rectangle that has a color with an alpha? I have:

windowSurface = pygame.display.set_mode((1000, 750), pygame.DOUBLEBUF)
pygame.draw.rect(windowSurface, pygame.Color(255, 255, 255, 128), pygame.Rect(0, 0, 1000, 750))

但我希望白色矩形的透明度为 50%,但 alpha 值似乎不起作用.

But I want the white rectangle to be 50% transparent, but the alpha value doesn't appear to be working.

推荐答案

pygame.draw 函数不会使用 alpha 进行绘制.文档说:

pygame.draw functions will not draw with alpha. The documentation says:

大多数参数接受颜色参数,即 RGB 三元组.这些也可以接受 RGBA 四元组.如果 Surface 包含像素 alpha,alpha 值将直接写入 Surface,但 draw 函数不会透明绘制.

Most of the arguments accept a color argument that is an RGB triplet. These can also accept an RGBA quadruplet. The alpha value will be written directly into the Surface if it contains pixel alphas, but the draw function will not draw transparently.

您可以做的是创建第二个表面,然后将其 blit 到屏幕上.Blitting 将进行 alpha 混合和颜色键.此外,您可以在表面级别(更快且内存更少)或像素级别(更慢但更精确)指定 alpha.你可以这样做:

What you can do is create a second surface and then blit it to the screen. Blitting will do alpha blending and color keys. Also, you can specify alpha at the surface level (faster and less memory) or at the pixel level (slower but more precise). You can do either:

s = pygame.Surface((1000,750))  # the size of your rect
s.set_alpha(128)                # alpha level
s.fill((255,255,255))           # this fills the entire surface
windowSurface.blit(s, (0,0))    # (0,0) are the top-left coordinates

或者,

s = pygame.Surface((1000,750), pygame.SRCALPHA)   # per-pixel alpha
s.fill((255,255,255,128))                         # notice the alpha value in the color
windowSurface.blit(s, (0,0))

请记住,在第一种情况下,您绘制到 s 的任何其他内容都将使用您指定的 alpha 值进行 blit.因此,例如,如果您使用它来绘制叠加控件,则最好使用第二种方法.

Keep in mind in the first case, that anything else you draw to s will get blitted with the alpha value you specify. So if you're using this to draw overlay controls for example, you might be better off using the second alternative.

另外,考虑使用 pygame.HWSURFACE 来创建表面硬件加速.

Also, consider using pygame.HWSURFACE to create the surface hardware-accelerated.

查看 pygame 站点上的 Surface 文档,尤其是介绍.

Check the Surface docs at the pygame site, especially the intro.

这篇关于在pygame中绘制一个透明矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆