在pygame中获取图像单个像素的颜色

3
我如何获取在pygame表面上贴图的像素颜色值?使用Surface.get_at()只能返回表面层的颜色,而不能返回贴图的图片颜色。

请提供您的代码示例 - Flint
1个回答

4
方法 surface.get_at 很好用。下面是一个示例,展示了没有 alpha 通道的图像 blitting 的差异。
import sys, pygame
pygame.init()
size = width, height = 320, 240
screen = pygame.display.set_mode(size)
image = pygame.image.load("./img.bmp")
image_rect = image.get_rect()

screen.fill((0,0,0))
screen.blit(image, image_rect)
screensurf = pygame.display.get_surface()

while 1:

  for event in pygame.event.get():
     if event.type == pygame.MOUSEBUTTONDOWN :
        mouse = pygame.mouse.get_pos()
        pxarray = pygame.PixelArray(screensurf)
        pixel = pygame.Color(pxarray[mouse[0],mouse[1]])
        print pixel
        print screensurf.get_at(mouse)

  pygame.display.flip()

在这里,点击红色像素会得到:
(0, 254, 0, 0)
(254, 0, 0, 255)

PixelArray返回的是0xAARRGGBB颜色组件,而Color需要0xRRGGBBAA。同时注意屏幕表面的alpha通道为255。


+1 很棒的回答!只有两个小问题:你提到了 surface.getAt,但实际上应该是 surface.get_at。这可能会让人感到困惑。其次,在 pygame.display.flip 函数中,你使用了一个未定义的变量 e。我不确定它应该是什么,而且由于字符太少,我无法自己编辑它。 - Ted Klein Bergman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接