Pabce
Pabce

Reputation: 1439

Drawn surface transparency in pygame?

I'm writing a predator-prey simulation using python and pygame for the graphical representation. I'm making it so you can actually "interact" with a creature (kill it, select it and follow it arround the world, etc). Right now, when you click a creature, a thick circle(made of various anti-aliased circles from the gfxdraw class) sorrounds it, meaning that you have succesfully selected it.

My goal is to make that circle transparent, but according to the documentation you can't set an alpha value for drawn surface. I have seen solutions for rectangles (by creating a separate semitransparent surface, blitting it, and then drawing the rectangle on it), but not for a semi-filled circle.

What do you suggest? Thank's :)

Upvotes: 5

Views: 8516

Answers (1)

sloth
sloth

Reputation: 101042

Have a look at the following example code:

import pygame

pygame.init()
screen = pygame.display.set_mode((300, 300))
ck = (127, 33, 33)
size = 25
while True:
  if pygame.event.get(pygame.MOUSEBUTTONDOWN):
    s = pygame.Surface((50, 50))

    # first, "erase" the surface by filling it with a color and
    # setting this color as colorkey, so the surface is empty
    s.fill(ck)
    s.set_colorkey(ck)

    pygame.draw.circle(s, (255, 0, 0), (size, size), size, 2)

    # after drawing the circle, we can set the 
    # alpha value (transparency) of the surface
    s.set_alpha(75)

    x, y = pygame.mouse.get_pos()
    screen.blit(s, (x-size, y-size))

  pygame.event.poll()
  pygame.display.flip()

enter image description here

Upvotes: 11

Related Questions