在pygame中画一条透明线

时间:2020-07-03 13:39:55

标签: python pygame

我需要一种在pygame中绘制部分透明的线的方法。我找到了这个答案(python - Draw a transparent Line in pygame),但它仅适用于直线,不适用于不同的线宽。

1 个答案:

答案 0 :(得分:1)

您必须创建具有任意大小和alpha通道的新表面

surface = pygame.Surface((width, height)).convert_alpha()

或使用主表面创建相同大小的新表面

surface = screen.convert_alpha()

使用透明颜色(0,0,0,0)填充它。重要的是最后一个零,表示alpha频道-(R,G,B,A)

surfaces.fill([0,0,0,0])

以小于255的alpha通道在此表面上绘制

pygame.draw.line(surface, (0, 0, 0, 32), (0, 0), (800, 600), 5)

最后,您可以在主页上的任意位置将其涂抹

screen.blit(surface, (x, y))

对于与主表面尺寸相同的表面,可以为(0,0)

screen.blit(surface, (0,0))

最小示例

import pygame

pygame.init()

screen = pygame.display.set_mode((800,600))#, depth=32)

surface1 = screen.convert_alpha()
surface1.fill([0,0,0,0])
pygame.draw.circle(surface1, (255, 0, 0, 128), (325, 250), 100)

surface2 = screen.convert_alpha()
surface2.fill([0,0,0,0])
pygame.draw.circle(surface2, (0, 255, 0, 128), (475, 250), 100)

surface3 = screen.convert_alpha()
surface3.fill([0,0,0,0])
pygame.draw.circle(surface3, (0, 0, 255, 128), (400, 350), 100)

surface4 = screen.convert_alpha()
surface4.fill([0,0,0,0])
pygame.draw.line(surface4, (0, 0, 0, 32), (0, 0), (800, 600), 5)
pygame.draw.line(surface4, (0, 0, 0, 32), (0, 600), (800, 0), 5)

surface5 = screen.convert_alpha()
surface5.fill([0,0,0,0])
pygame.draw.polygon(surface5, (255, 0, 0, 128), [(400, 250), (450, 300), (400, 350), (350, 300)])

screen.fill([255,255,255]) # white background
screen.blit(surface1, (0,0))
screen.blit(surface2, (0,0))
screen.blit(surface3, (0,0))
screen.blit(surface4, (0,0))
screen.blit(surface5, (0,0))

pygame.display.flip()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

pygame.quit()    

enter image description here

相关问题