How to make transparent pygame.draw.circle [duplicate]

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-16 18:00:32

问题


How to make pygame.draw.circle transparent (add alpha level), as for "surface" "set_alpha"? I found a solution only in changing the color of pygame.draw.circle to less bright


回答1:


You've to use a pygame.Surface. Create a Surface with a per pixel alpha image format. e.g:

radius = 100
circle = pygame.Surface((radius*2, radius*2), pygame.SRCALPHA)

And draw a transparent circle on it. The color of the circle has to have an alpha channel < 255 (e.g. 128):

pygame.draw.circle(circle, (255, 0, 0, 128), (radius, radius), radius)

blit() the Surface to the window. e.g.:

window.blit(circle, (100, 100))

Example:

import pygame

pygame.init()
wndsize = (400, 400)
window = pygame.display.set_mode(wndsize)
clock = pygame.time.Clock()

run = True
while run:
    clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.fill(0)
    pygame.draw.rect(window, (0, 0, 255), (0, 0, 200, 400))

    radius = 100
    circle = pygame.Surface((radius*2, radius*2), pygame.SRCALPHA)   
    pygame.draw.circle(circle, (255, 0, 0, 128), (radius, radius), radius)
    window.blit(circle, (100, 100))

    pygame.display.flip()



回答2:


You can create surface with alpha channel

 surface1 = screen.convert_alpha()

fill it with transparent color -

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

draw circle using color [R,G,B,Alpha]

 pygame.draw.circle(surface1, (255, 0, 0, 128), (300, 300), 200)

and blit it on screen

 screen.blit(surface1, (0,0))

But alpha always mix object color with background color so it makes it less bright.


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)

screen.fill([255,255,255]) # white background
screen.blit(surface1, (0,0))
screen.blit(surface2, (0,0))
screen.blit(surface3, (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()    


Example on GitHub: furas/python-examples/pygame/transparency



来源:https://stackoverflow.com/questions/59293057/how-to-make-transparent-pygame-draw-circle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!