Skip to main content
 首页 » 编程设计

python之如何在pygame中绘制透明线

2025年05月04日12xing901022

我做了一个小游戏,我需要一个带线条的背景图案。由于性能更好,我想用 Python 绘制图案而不是拍摄图像。

问题是我找不到绘制透明线条的方法。有面的解决方案,但线没有。

这是模式代码:

import pygame 
from math import pi 
 
pygame.init() 
 
size = [600, 600] 
screen = pygame.display.set_mode(size) 
 
while True: 
 
    for i in range(0, 600, 20): 
        pygame.draw.aaline(screen, (0, 255, 0), [i, 0],[i, 600], True) 
        pygame.draw.aaline(screen, (0, 255, 0), [0, i],[600, i], True) 
 
    pygame.display.flip() 
  
pygame.quit() 

有没有人有解决办法?

请您参考如下方法:

我花了一点点时间来敲打自己的脑袋,但我最终明白了。 Pygame.draw 不会处理透明度,因此您必须制作单独的表面:

import pygame from math import pi 
 
pygame.init() 
 
size = [600, 600] screen = pygame.display.set_mode(size) 
while True: 
    screen.fill((0, 0, 0)) 
    for i in range(0, 600, 20): 
        vertical_line = pygame.Surface((1, 600), pygame.SRCALPHA) 
        vertical_line.fill((0, 255, 0, 100)) # You can change the 100 depending on what transparency it is. 
        screen.blit(vertical_line, (i - 1, 0)) 
        horizontal_line = pygame.Surface((600, 1), pygame.SRCALPHA) 
        horizontal_line.fill((0, 255, 0, 100)) # You can change the 100 depending on what transparency it is. 
        screen.blit(horizontal_line, (0, i - 1)) 
 
    pygame.display.flip() 
 
pygame.quit() 

我希望这就是您要找的。