【发布时间】:2021-12-23 22:21:47
【问题描述】:
我在 PyGame 中有一个 Surface。我想直接修改像素的 alpha 值。我尝试过使用各种访问 alpha 值的方法,但它们似乎不起作用。
from screeninfo import get_monitors
import pygame, os, numpy.random, pygame.surfarray
pygame.init()
FPS = 60
CLOCK = pygame.time.Clock()
monitor_info = get_monitors()
x = 0
y = 0
width = monitor_info[0].width
height = monitor_info[0].height
if len(monitor_info) > 1:
if monitor_info[0].x < 0:
x = 0
else:
x = monitor_info[0].width
width = monitor_info[1].width
height = monitor_info[1].height
os.environ['SDL_VIDEO_WINDOW_POS'] = "{},0".format(x)
pygame.display.init()
pygame.mouse.set_visible(False)
screen_info = pygame.display.Info()
screen_size = width, height
base_screen = pygame.display.set_mode(screen_size, pygame.NOFRAME)
base_screen.fill([100, 100, 100])
board_size = (int(min(width, height)*0.75), int(min(width, height)*0.75))
surface = pygame.Surface(board_size, pygame.SRCALPHA)
surface.fill([255, 255, 255, 255])
base_screen.blit(surface, (0,0))
pygame.display.flip()
pixels = numpy.random.uniform(low=0, high=255, size=(board_size[0], board_size[1], 3))
transparency = numpy.random.uniform(low=0, high=255, size=board_size).astype('uint8')
while True:
events = pygame.event.get()
ms = CLOCK.tick(FPS)
print('\r {} '.format(ms), end='')
# pygame.surfarray.blit_array(surface, pixels)
aa = pygame.surfarray.pixels_alpha(surface)
aa = numpy.random.uniform(low=0, high=255, size=board_size).astype('uint8')
del aa
# for i in range(board_size[0]):
# for j in range(board_size[1]):
# a = surface.get_at((i,j))
# a[3] = 0
# surface.set_at((i,j), a)
base_screen.blit(surface, (0,0))
pygame.display.flip()
我已经在循环中尝试了这两种方法(pixels_array 和 get_at/set_at),但都不起作用——图像只是保持白色(如果我将初始 alpha 设置为 0,它会保持透明)。有谁知道如何为 Surface 设置每个像素的 alpha 值?
【问题讨论】:
-
只是为了确保您理解,当您说
aa = ...pixels_alpha和aa = numpy.random.uniform时,您确实明白第二个语句不会影响表面,对吧?这会获取一组 alpha 值,然后将其丢弃并将名称重新分配给 numpy 中的随机数。 -
您注释掉的
for循环看起来很正确。那没有用吗?get_buffer也可以使用,如果您可以进行像素寻址。 -
看起来已经有了答案,但就我自己而言:根据文档,pixels_alpha 调用创建了一个参考:pygame.org/docs/ref/…。我的第二行是否只是重新分配变量的引用而不是修改引用?
-
对。请记住,名称只是对对象的引用。当您说
aa = ...时,它会在aa中存储对新对象的新引用。旧参考已发布。
标签: python pygame alpha-transparency