def style(srf, bg=None, border=(0,0,0), weight=0, padding=0):
"Create a new surface with padding, background color, and/or border"
w, h = srf.get_size()
# Add padding
padding += weight
w += 2 * padding
h += 2 * padding
img = pygame.Surface((w, h), pygame.SRCALPHA)
# Add background color and border
if bg: img.fill(rgba(bg))
img.blit(srf, (padding, padding))
if weight: drawBorder(img, border, weight)
return img
python类SRCALPHA的实例源码
def test_render(self):
csv = textwrap.dedent(self.TILEMAP_CSV).strip()
tilemap = (sappho.tiles.TileMap.
from_csv_string_and_tilesheet(csv, self.tilesheet))
# Create a surface that has 1x2 strips of red, green, and
# blue to against the rendered tilemap. This surface has
# to have the SRCALPHA flag and a depth of 32 to match
# the surface returned by the render function.
test_surface = pygame.surface.Surface((3, 2), pygame.SRCALPHA, 32)
test_surface.fill((255, 0, 0), pygame.Rect(0, 0, 1, 2))
test_surface.fill((0, 255, 0), pygame.Rect(1, 0, 1, 2))
test_surface.fill((0, 0, 255), pygame.Rect(2, 0, 1, 2))
# Render the tilemap
output_surface = tilemap.to_surface()
# Compare the two surfaces
assert(compare_surfaces(test_surface, output_surface))
def create_surface_layers(target_surface, number_of_layers):
"""Create a list of pygame surfaces
the size of the target surface.
Arguments:
target_surface (pygame.Surface): The surface
whose dimensions will be used for each layer.
number_of_layers (int): The number of surfaces to
create/return.
Returns:
list[pygame.Surface]: List of surfaces
"""
surface_layers = []
for i in range(number_of_layers):
surface = pygame.surface.Surface(target_surface.get_size(),
pygame.SRCALPHA, 32)
surface_layers.append(surface)
return surface_layers
def __init__(self, source_resolution, output_resolution,
view_resolution, behavior=None):
"""Create a Camera!
Arguments:
view_resolution (tuple[int, int]): used to create
view_rect attribute.
"""
super(Camera, self).__init__(output_resolution)
self.source_surface = pygame.surface.Surface(source_resolution,
pygame.SRCALPHA)
self.source_resolution = source_resolution
self.output_resolution = output_resolution
self.view_rect = pygame.Rect((0, 0), view_resolution)
self.behavior = behavior or CameraBehavior()
def snapshot(self):
"Capture the canvas as an Image instance"
srf = pygame.Surface(self.size, pygame.SRCALPHA)
# Draw background
if isinstance(self._bg, Image):
self._bg.config(size=self._size)
srf.blit(self._bg.image, (0,0))
elif self._bg: srf.fill(self._bg)
# Draw objects
for g in self:
if g.snapshot is not None:
xy = g.blitPosition((0,0), g.size)
srf.blit(g.snapshot().image, xy)
else: g.draw(srf, snapshot=True)
# Draw border
if self.weight: drawBorder(srf, self.border, self.weight)
return Image(srf)
def main():
pygame.init()
screen = pygame.display.set_mode((500,500))
screen.fill((255, 0, 0))
s = pygame.Surface(screen.get_size(), pygame.SRCALPHA, 32)
pygame.draw.line(s, (0,0,0), (250, 250), (250+200,250))
width = 1
for a_radius in range(width):
radius = 200
pygame.gfxdraw.aacircle(s, 250, 250, radius-a_radius, (0, 0, 0))
screen.blit(s, (0, 0))
pygame.display.flip()
try:
while 1:
event = pygame.event.wait()
if event.type == pygame.QUIT:
break
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE or event.unicode == 'q':
break
pygame.display.flip()
finally:
pygame.quit()
def test_save_colorkey(self):
""" make sure the color key is not changed when saving.
"""
s = pygame.Surface((10,10), pygame.SRCALPHA, 32)
s.fill((23,23,23))
s.set_colorkey((0,0,0))
colorkey1 = s.get_colorkey()
p1 = s.get_at((0,0))
temp_filename = "tmpimg.png"
try:
pygame.image.save(s, temp_filename)
s2 = pygame.image.load(temp_filename)
finally:
os.remove(temp_filename)
colorkey2 = s.get_colorkey()
# check that the pixel and the colorkey is correct.
self.assertEqual(colorkey1, colorkey2)
self.assertEqual(p1, s2.get_at((0,0)))
def test_copy(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.copy:
# Surface.copy(): return Surface
# create a new copy of a Surface
color = (25, 25, 25, 25)
s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
s1.fill(color)
s2 = s1.copy()
s1rect = s1.get_rect()
s2rect = s2.get_rect()
self.assert_(s1rect.size == s2rect.size)
self.assert_(s2.get_at((10,10)) == color)
def test_fill(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.fill:
# Surface.fill(color, rect=None, special_flags=0): return Rect
# fill Surface with a solid color
color = (25, 25, 25, 25)
fill_rect = pygame.Rect(0, 0, 16, 16)
s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
s1.fill(color, fill_rect)
for pt in test_utils.rect_area_pts(fill_rect):
self.assert_(s1.get_at(pt) == color )
for pt in test_utils.rect_outer_bounds(fill_rect):
self.assert_(s1.get_at(pt) != color )
def test_fill_negative_coordinates(self):
# negative coordinates should be clipped by fill, and not draw outside the surface.
color = (25, 25, 25, 25)
color2 = (20, 20, 20, 25)
fill_rect = pygame.Rect(-10, -10, 16, 16)
s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
r1 = s1.fill(color, fill_rect)
c = s1.get_at((0,0))
self.assertEqual(c, color)
# make subsurface in the middle to test it doesn't over write.
s2 = s1.subsurface((5, 5, 5, 5))
r2 = s2.fill(color2, (-3, -3, 5, 5))
c2 = s1.get_at((4,4))
self.assertEqual(c, color)
# rect returns the area we actually fill.
r3 = s2.fill(color2, (-30, -30, 5, 5))
# since we are using negative coords, it should be an zero sized rect.
self.assertEqual(tuple(r3), (0, 0, 0, 0))
def test_get_alpha(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.get_alpha:
# Surface.get_alpha(): return int_value or None
# get the current Surface transparency value
s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
self.assert_(s1.get_alpha() == 255)
for alpha in (0, 32, 127, 255):
s1.set_alpha(alpha)
for t in range(4): s1.set_alpha(s1.get_alpha())
self.assert_(s1.get_alpha() == alpha)
########################################################################
def test_set_colorkey(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.set_colorkey:
# Surface.set_colorkey(Color, flags=0): return None
# Surface.set_colorkey(None): return None
# Set the transparent colorkey
s = pygame.Surface((16,16), pygame.SRCALPHA, 32)
colorkeys = ((20,189,20, 255),(128,50,50,255), (23, 21, 255,255))
for colorkey in colorkeys:
s.set_colorkey(colorkey)
for t in range(4): s.set_colorkey(s.get_colorkey())
self.assertEquals(s.get_colorkey(), colorkey)
def __init__(self, x, y, sceneData, max_health=10):
super().__init__()
self.name = "ChargePad"
self.frameAnimationSpeed = 15
imageBase = pygame.image.load(os.path.join('img', 'unbranded-cola.png'))
imageRot = pygame.transform.rotate(imageBase, 10)
imageRot2 = pygame.transform.rotate(imageBase, 20)
imageRot3 = pygame.transform.rotate(imageBase, -10)
frames = [imageRot3,imageBase, imageRot,imageRot2,imageRot,imageBase]
self.animation = Animation(frames, self.frameAnimationSpeed, True)
self.image = frames[0]
self.imageTransparent = pygame.Surface((1, 1),pygame.SRCALPHA)
self.rect = self.image.get_rect() # Position centrée du player
self.x = x
self.y = y
self.rect.x = x
self.rect.y = y
self.sceneData = sceneData
def __init__(self, x, y, sceneData, max_health=10):
super().__init__()
self.name = "ChargePad"
self.frameAnimationSpeed = 20
imageBase = pygame.image.load(os.path.join('img', 'charge-pad.png'))
imageFlash = pygame.image.load(os.path.join('img', 'charge-pad-flash.png'))
frames = [imageBase, imageFlash]
self.animation = Animation(frames, self.frameAnimationSpeed, True)
self.image = frames[0]
self.imageTransparent = pygame.Surface((1, 1),pygame.SRCALPHA)
self.rect = self.image.get_rect() # Position centrée du player
self.x = x
self.y = y
self.rect.x = x
self.rect.y = y
self.sceneData = sceneData
def draw_car(self, player_data):
"""
???
"""
carImagePath = self.theme + ('/mycar.png' if player_data.name is self.current_player.name else "/car.png")
carImage = pygame.image.load(carImagePath).convert(32, pygame.SRCALPHA)
rotatedCar = pygame.transform.rotate(carImage, -player_data.rotation * 180 / math.pi)
carRect = rotatedCar.get_rect()
carRect.center = self.calculate_offset(player_data.pos_x, player_data.pos_y)
self.surf.blit(rotatedCar, carRect)
font = pygame.font.Font('font/wqy-microhei.ttc', 18)
nameSurf = font.render(player_data.name, True, Constants.NAME_COLOR)
nameRect = nameSurf.get_rect()
nameRect.center = self.calculate_offset(player_data.pos_x, player_data.pos_y - 48)
# FIXME: ??????????? ??????
surf.fill(NAMEBG, nameRect)
self.surf.blit(nameSurf, nameRect)
def __init__(self, x, y, color, direction, speed, container, brain = None):
pygame.sprite.Sprite.__init__(self, container)
self.image = pygame.Surface((16,16), flags=pygame.SRCALPHA)
self.rect = self.image.get_rect()
basex = 423
if color==RED:
basex += 96
## Generate the sprite image from spritesheet
ssrect = pygame.Rect((basex,710,16,16))
global spritesheet
self.image.blit(spritesheet,(0,0),ssrect)
self.rect = self.image.get_rect()
self.rect.center = (x, y)
self.direction = direction
self.speed = speed
self.brain = brain
def draw(self,surface):
rad2 = Vector(self.radius,self.radius)
if self.idle: # Range-circle
surf = pg.Surface((self.shot_range*2,)*2, pg.SRCALPHA)
pg.draw.circle(surf, (0,0,255,50), (self.shot_range,)*2, self.shot_range)
surface.blit(surf, self.pos-(self.shot_range,)*2)
pg.draw.circle(surface, (0,0,255), self.pos, self.shot_range,3)
# Tower itself
render_image = pg.transform.rotozoom(self.image,-self.angle,1) # rotozoom for a bit AA
draw_center = self.pos - Vector( *render_image.get_size() )/2
surface.blit(render_image, draw_center)
if not self.placeable: # Red circle, if not allowed to place
aSurf = pg.Surface((self.radius*2,)*2, pg.SRCALPHA)
aSurf.convert_alpha()
radius = int(self.radius)
pg.draw.circle(aSurf,(255,0,0,50), rad2, radius)
pg.draw.circle(aSurf,(255,0,0,250), rad2, radius, 3)
surface.blit(aSurf,draw_center)
def __init__(self, ls, w, h, l, t, value):
pygame.sprite.Sprite.__init__(self)
self.ls = ls
self.w = w
self.h = h
self.left = l
self.top = t
self.focus_order = -1
if self.ls.lang.ltr_text:
self.right_align = False
else:
self.right_align = True
self.font_color = self.ls.colors.font_color
self.value = value
self.select_item = False
self.update_me = True
self.image = pygame.Surface([w, h], flags=pygame.SRCALPHA)
self.rect = self.image.get_rect()
self.rect.topleft = [l, t]
self.font_v = self.ls.font_2
def layout_update(self):
self.color = (255, 255, 255, 150)
self.scheme = "white"
if self.game_board.mainloop.scheme is not None:
if self.game_board.mainloop.scheme.dark:
self.scheme = "black"
self.color = (0, 0, 0, 150)
self.width = self.layout.game_w
self.height = self.layout.game_h
self.image = pygame.Surface([self.width, self.height], flags=pygame.SRCALPHA)
self.image.fill(self.color)
self.rect = self.image.get_rect()
self.rect.topleft = [0, 0]
self.img = pygame.image.load(os.path.join('res', 'images', self.img_src)).convert_alpha()
self.img2 = pygame.image.load(os.path.join('res', 'images', self.img_src2)).convert_alpha()
# img2 has the same size
img_pos_x = self.img.get_rect(centerx=self.image.get_width() // 2)
img_pos_y = self.img.get_rect(centery=self.image.get_height() // 2)
self.img_pos = (img_pos_x[0], img_pos_y[1])
def generate_images(font):
# generate a scanline image to create scanline effect
scanline = pygame.Surface((glyph_width, glyph_height), pygame.SRCALPHA)
for y in range(0, glyph_height, 2):
pygame.draw.line(scanline, (0, 0, 0, 128), (0, y), (glyph_width, y))
# render all characters a head of time
for char in charset:
chars = list()
cache.append(chars)
for value in computed_values:
color = calc_color(value)
temp = font.render(char, 1, color)
temp = pygame.transform.smoothscale(temp, (glyph_width, glyph_height))
temp.blit(scanline, (0, 0))
image = pygame.Surface(temp.get_size())
image.blit(temp, (0, 0))
chars.append(image)
def get_tile(self, image_name, clip_x, clip_y):
if image_name not in self.images:
s = pygame.Surface((self.tile_size,self.tile_size))
s.fill((0,0,0))
return s
surface = self.images[image_name]
rect = pygame.Rect(
(
clip_x*self.tile_size,
clip_y*self.tile_size,
self.tile_size,
self.tile_size
)
)
image = pygame.Surface(rect.size, pygame.SRCALPHA)
image.fill((0,0,0,0))
image.blit(surface, (0, 0), rect)
return image
def render(self):
surface = pygame.Surface(self.parent.resolution)
for y in range(self.fireworks.get_height()):
for x in range(self.fireworks.get_width()):
node = self.fireworks.get_cell(x,y)
if node > 0:
pygame.draw.rect(surface, colours.COLOUR_YELLOW, (x*self.firework_size, y*self.firework_size, self.firework_size, self.firework_size))
surface.blit(self.congratulations_text,
((surface.get_width()-self.congratulations_text.get_width())/2,
surface.get_height()/2 - 150)
)
surface.blit(
self.team1_text,
((surface.get_width()-self.team1_text.get_width())/2,
(surface.get_height()-self.team1_text.get_height())/2)
)
mask = pygame.Surface(self.parent.resolution, pygame.SRCALPHA)
mask.fill((0,0,0, 255-self.alpha))
surface.blit(mask, (0,0))
return surface
def render(self):
surface = pygame.Surface(self.root.resolution)
if self.cur_animation < 3:
banner = self.versus_banner.render()
surface.blit(banner,
(
(surface.get_width()-banner.get_width())//2,
(surface.get_height()-banner.get_height())//2
)
)
else:
window = self.battle_window.render()
status = self.mage_status.render()
window.blit(status, (0, window.get_height()-200))
round_count = self.round_counter.render()
window.blit(round_count, self.round_counter.get_pos())
surface.blit(window, (0,0))
mask = pygame.Surface(self.root.resolution, pygame.SRCALPHA)
mask.fill((0,0,0, 255-self.alpha))
surface.blit(mask, (0,0))
return surface
def main():
pygame.init()
screen = pygame.display.set_mode((500,500))
screen.fill((255, 0, 0))
s = pygame.Surface(screen.get_size(), pygame.SRCALPHA, 32)
pygame.gfxdraw.aacircle(s, 250, 250, 200, (0, 0, 0))
screen.blit(s, (0, 0))
pygame.display.flip()
try:
while 1:
event = pygame.event.wait()
if event.type == pygame.QUIT:
break
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE or event.unicode == 'q':
break
pygame.display.flip()
finally:
pygame.quit()
def test_copy(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.copy:
# Surface.copy(): return Surface
# create a new copy of a Surface
color = (25, 25, 25, 25)
s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
s1.fill(color)
s2 = s1.copy()
s1rect = s1.get_rect()
s2rect = s2.get_rect()
self.assert_(s1rect.size == s2rect.size)
self.assert_(s2.get_at((10,10)) == color)
def test_get_alpha(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.get_alpha:
# Surface.get_alpha(): return int_value or None
# get the current Surface transparency value
s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
self.assert_(s1.get_alpha() == 255)
for alpha in (0, 32, 127, 255):
s1.set_alpha(alpha)
for t in range(4): s1.set_alpha(s1.get_alpha())
self.assert_(s1.get_alpha() == alpha)
########################################################################
def test_set_colorkey(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.set_colorkey:
# Surface.set_colorkey(Color, flags=0): return None
# Surface.set_colorkey(None): return None
# Set the transparent colorkey
s = pygame.Surface((16,16), pygame.SRCALPHA, 32)
colorkeys = ((20,189,20, 255),(128,50,50,255), (23, 21, 255,255))
for colorkey in colorkeys:
s.set_colorkey(colorkey)
for t in range(4): s.set_colorkey(s.get_colorkey())
self.assertEquals(s.get_colorkey(), colorkey)
def todo_test_blit__SRCALPHA_to_SRCALPHA_non_zero(self): #TODO
# " There is no unit test for blitting a SRCALPHA source with non-zero
# alpha to a SRCALPHA destination with non-zero alpha " LL
w,h = size = 32,32
s = pygame.Surface(size, pygame.SRCALPHA, 32)
s2 = s.copy()
s.fill((32,32,32,111))
s2.fill((32,32,32,31))
s.blit(s2, (0,0))
# TODO:
# what is the correct behaviour ?? should it blend? what algorithm?
self.assertEquals(s.get_at((0,0)), (32,32,32,31))
def setSize(self, size):
self.geometry = size
self.geometry2 = [self.geometry[0]+13,self.geometry[1]+29]
self.pos2 = (self.pos[0]+self.geometry2[0], self.pos[1]+self.geometry2[1])
self.pos3 = (self.pos[0]+self.geometry2[0]/2, self.pos[1]+self.geometry2[1]/2)
self.surface = pygame.Surface((self.geometry[0], self.geometry[1]))
self.surfaceTemp = pygame.Surface((self.geometry[0], self.geometry[1]))
self.widgetSurface = pygame.Surface((self.geometry[0], self.geometry[1]), pygame.SRCALPHA, 32)
self.animStage = [self.geometry[0],self.geometry[1]]
self.animDone = True
self.widgets = []
if (not self.oldWidgets == None) or (not self.oldWidgets == []):
for widget in self.oldWidgets:
if type(widget) is str:
self.widgets += [eval(widget)]
self.widgets[len(self.widgets)-1].setScreen(self.widgetSurface, self.sysRes, self.sysVar)
def __init__(self, workQueue, queueLock, dataDir):
super(Extension, self).__init__() # super() will call Thread.__init__ for you
self.workQueue = workQueue
self.queueLock = queueLock
self.tData = ['', [], 'Extension']
self.hasQueue = False
print (pygame.display.Info().current_w, pygame.display.Info().current_h)
self.screenTemp = pygame.Surface((pygame.display.Info().current_w, pygame.display.Info().current_h), pygame.SRCALPHA, 32)
'''Used by the WM to prevent flickering'''
self.screen = pygame.Surface((pygame.display.Info().current_w, pygame.display.Info().current_h), pygame.SRCALPHA, 32)
'''Screen buffer that extensions draw on'''
self._stop = threading.Event()
self.dataDir = dataDir
self.errorData = None
self.args = None
self.extName = "Unnamed Extension"
#self.screen.fill((255,255,255,255))