[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

RE: [pygame] Determining per-pixel alpha



How can I tell if a surface has per-pixel alpha?

I wrote this function to scale an arbitrary surface, but it fails if
the surface has per-pixel alpha (the background shows up
TRANSPARENT instead of transparent) with this output:


Hm... I changed my TRANSPARENT color to have an alpha channel
and now it works the way I want... That's good. I am still a bit fuzzy
on the distinctions between colorkey, alpha, and per-pixel alpha
though, if someone feels like explaining something :o)


import pygame
TRANSPARENT = (0, 51, 0, 0)
def scale_image(img, width, height, keepAspectRatio=1):
"""return a scaled copy of a L{pygame.Surface}

@param img: Original L{pygame.Surface}.
@param width: width of returned surface.
@param height: height of returned surface.
@param keepAspectRatio: If True, the returned surface will be padded with
transparent borders.

"""

if keepAspectRatio:
flags = img.get_flags()
new_img = pygame.Surface((width, height), flags, img)

img_w, img_h = img.get_size()
ratio = float(img_w) / img_h
new_ratio = float(width) / height

colorkey = img.get_colorkey()
if colorkey is None:
colorkey = TRANSPARENT
new_img.fill(colorkey)
new_img.set_colorkey(colorkey)

alpha = img.get_alpha()
if alpha is not None:
new_img.set_alpha(alpha)

if ratio >= new_ratio:
new_w = int(width)
new_h = int(float(new_w) / ratio)
x = 0
y = (height - new_h) / 2
else:
new_h = int(height)
new_w = int(float(new_h) * ratio)
x = (width - new_w) / 2
y = 0

scaled_img = pygame.transform.scale(img, (new_w, new_h))
new_img.blit(scaled_img, (x, y))

else:
new_img = pygame.transform.scale(img, (width, height))

return new_img

_________________________________________________________________
Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail