我正在使用 pygame 项目,我需要我的游戏立方体具有 NEON 效果。 pygame 是否有一个函数可以制作 NEON 效果或类似这样的功能:
pygame.draw.rect(win, (255, 0, 255[neon]), ...)
最佳答案
Pygame 没有“glow”、“bllom”或“neon”功能。您必须使用cv2和/或 numpy来创造这样的效果。
编写一个对 pygame.Surface
应用效果的函数:
- 使用
pygame.surfarray.array3d
转换pygame.Surface
到 3D 数组。 - 使用cv2对图像应用效果(例如
cv2.blur
)。 - 使用
pygame.image.frombuffer
将 3D 数组转换回pygame.Surface
(参见How do I convert an OpenCV (cv2) image (BGR and BGRA) to a pygame.Surface object:
def create_neon(surf):
surf_alpha = surf.convert_alpha()
rgb = pygame.surfarray.array3d(surf_alpha)
alpha = pygame.surfarray.array_alpha(surf_alpha).reshape((*rgb.shape[:2], 1))
image = numpy.concatenate((rgb, alpha), 2)
cv2.GaussianBlur(image, ksize=(9, 9), sigmaX=10, sigmaY=10, dst=image)
cv2.blur(image, ksize=(5, 5), dst=image)
bloom_surf = pygame.image.frombuffer(image.flatten(), image.shape[1::-1], 'RGBA')
return bloom_surf
最小示例:
import pygame
import numpy
import cv2
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
def create_neon(surf):
surf_alpha = surf.convert_alpha()
rgb = pygame.surfarray.array3d(surf_alpha)
alpha = pygame.surfarray.array_alpha(surf_alpha).reshape((*rgb.shape[:2], 1))
image = numpy.concatenate((rgb, alpha), 2)
cv2.GaussianBlur(image, ksize=(9, 9), sigmaX=10, sigmaY=10, dst=image)
cv2.blur(image, ksize=(5, 5), dst=image)
bloom_surf = pygame.image.frombuffer(image.flatten(), image.shape[1::-1], 'RGBA')
return bloom_surf
image = pygame.Surface((100, 100), pygame.SRCALPHA)
pygame.draw.rect(image, (255, 128, 128), (10, 10, 80, 80))
neon_image = create_neon(image)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill((127, 127, 127))
window.blit(neon_image, neon_image.get_rect(center = window.get_rect().center), special_flags = pygame.BLEND_PREMULTIPLIED)
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()
关于python - pygame 中的 NEON 效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67933919/