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类Surface()的实例源码
def render(self, text, antialias, forecolor, backcolor=(0,0,0,255)):
size = self.size(text)
img = NSImage.alloc().initWithSize_(size)
img.lockFocus()
NSString.drawAtPoint_withAttributes_(text, (0.0, 0.0), {
NSFontAttributeName: self._font,
NSUnderlineStyleAttributeName: self._isUnderline and 1.0 or None,
NSBackgroundColorAttributeName: backcolor and _getColor(backcolor) or None,
NSForegroundColorAttributeName: _getColor(forecolor),
})
rep = NSBitmapImageRep.alloc().initWithFocusedViewRect_(((0.0, 0.0), size))
img.unlockFocus()
if rep.samplesPerPixel() == 4:
s = Surface(size, SRCALPHA|SWSURFACE, 32, [-1<<24,0xff<<16,0xff<<8,0xff])
a = Numeric.reshape(Numeric.fromstring(rep.bitmapData(), typecode=Numeric.Int32), (size[1], size[0]))
blit_array(s, Numeric.swapaxes(a,0,1))
return s.convert_alpha()
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 __getitem__(self, key):
"""Access a surface by z-index.
Arguments:
key (int): The z-index of the surface.
Raises:
IndexError: When the z-index is invalid.
Returns:
pygame.Surface: The surface belonging
to the z-index specified.
"""
return self._surface_layers[key]
def _draw_title_text(mdp, screen):
'''
Args:
mdp (simple_rl.MDP)
screen (pygame.Surface)
Summary:
Draws the name of the MDP to the top of the screen.
'''
scr_width, scr_height = screen.get_width(), screen.get_height()
title_split = str(mdp).split("_")
title = title_split[0]
param_text = " ("
for param in title_split[1:-1]:
param_text += param + ", "
param_text += title_split[-1] + ")"
formatted_title_text = title[0].upper() + title[1:] + param_text
title_text = title_font.render(formatted_title_text, True, (46, 49, 49))
screen.blit(title_text, (scr_width / 2.0 - len(formatted_title_text)*6, scr_width / 20.0))
def _draw_state_text(state, screen):
'''
Args:
state (simple_rl.State)
screen (pygame.Surface)
Summary:
Draws the name of the current state to the bottom left of the screen.
'''
scr_width, scr_height = screen.get_width(), screen.get_height()
# Clear.
formatted_state_text = str(state)
if len(formatted_state_text) > 20:
# State text is too long, ignore.
return
state_text_point = (scr_width / 4.0 - len(formatted_state_text)*6, 18*scr_height / 20.0)
pygame.draw.rect(screen, (255,255,255), (state_text_point[0] - 20, state_text_point[1]) + (200,40))
state_text = title_font.render(formatted_state_text, True, (46, 49, 49))
screen.blit(state_text, state_text_point)
def _draw_agent(center_point, screen, base_size=30):
'''
Args:
center_point (tuple): (x,y)
screen (pygame.Surface)
Returns:
(pygame.rect)
'''
# taxi_image = pygame.image.load("taxi.png")
# image_rect = taxi_image.get_rect()
tri_bot_left = center_point[0] - base_size, center_point[1] + base_size
tri_bot_right = center_point[0] + base_size, center_point[1] + base_size
tri_top = center_point[0], center_point[1] - base_size
tri = [tri_bot_left, tri_top, tri_bot_right]
tri_color = (98, 140, 190)
# screen.blit(taxi_image, image_rect)
# return image_rect
return pygame.draw.polygon(screen, tri_color, tri)
def __init__(self, srf, bg=None, decompress=zlib.decompress):
if hasattr(srf, "image"): srf = srf.image
t = type(srf)
if t is str:
srf = pygame.image.load(srf)
if bg: srf = style(srf, bg)
elif not hasAlpha(srf): srf = srf.convert_alpha()
elif t is bytes:
mode, w, h = struct.unpack("!3I", bg)
if mode & 2: srf = decompress(srf)
mode = "RGBA" if mode & 1 else "RGB"
srf = pygame.image.fromstring(srf, (w,h), mode)
elif t in (list, tuple):
srf = pygame.Surface(srf, pygame.SRCALPHA)
if bg: srf.fill(bg if type(bg) is pygame.Color else rgba(bg))
self.original = srf
self.dumpCache()
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 surfdemo_show(array_img, name):
"displays a surface, waits for user to continue"
screen = pygame.display.set_mode(array_img.shape[:2], 0, 32)
surfarray.blit_array(screen, array_img)
pygame.display.flip()
pygame.display.set_caption(name)
while 1:
e = pygame.event.wait()
if e.type == MOUSEBUTTONDOWN: break
elif e.type == KEYDOWN and e.key == K_s:
#pygame.image.save(screen, name+'.bmp')
#s = pygame.Surface(screen.get_size(), 0, 32)
#s = s.convert_alpha()
#s.fill((0,0,0,255))
#s.blit(screen, (0,0))
#s.fill((222,0,0,50), (0,0,40,40))
#pygame.image.save_extended(s, name+'.png')
#pygame.image.save(s, name+'.png')
#pygame.image.save(screen, name+'_screen.png')
#pygame.image.save(s, name+'.tga')
pygame.image.save(screen, name+'.png')
elif e.type == QUIT:
raise SystemExit()
def test_rect__one_pixel_lines(self):
# __doc__ (as of 2008-06-25) for pygame.draw.rect:
# pygame.draw.rect(Surface, color, Rect, width=0): return Rect
# draw a rectangle shape
rect = pygame.Rect(10, 10, 56, 20)
drawn = draw.rect(self.surf, self.color, rect, 1)
self.assert_(drawn == rect)
#Should be colored where it's supposed to be
for pt in test_utils.rect_perimeter_pts(drawn):
color_at_pt = self.surf.get_at(pt)
self.assert_(color_at_pt == self.color)
#And not where it shouldn't
for pt in test_utils.rect_outer_bounds(drawn):
color_at_pt = self.surf.get_at(pt)
self.assert_(color_at_pt != self.color)
def todo_test_arc(self):
# __doc__ (as of 2008-08-02) for pygame.draw.arc:
# pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle,
# width=1): return Rect
#
# draw a partial section of an ellipse
#
# Draws an elliptical arc on the Surface. The rect argument is the
# area that the ellipse will fill. The two angle arguments are the
# initial and final angle in radians, with the zero on the right. The
# width argument is the thickness to draw the outer edge.
#
self.fail()
def todo_test_lines(self):
# __doc__ (as of 2008-08-02) for pygame.draw.lines:
# pygame.draw.lines(Surface, color, closed, pointlist, width=1): return Rect
# draw multiple contiguous line segments
#
# Draw a sequence of lines on a Surface. The pointlist argument is a
# series of points that are connected by a line. If the closed
# argument is true an additional line segment is drawn between the
# first and last points.
#
# This does not draw any endcaps or miter joints. Lines with sharp
# corners and wide line widths can have improper looking corners.
#
self.fail()
def todo_test_polygon(self):
# __doc__ (as of 2008-08-02) for pygame.draw.polygon:
# pygame.draw.polygon(Surface, color, pointlist, width=0): return Rect
# draw a shape with any number of sides
#
# Draws a polygonal shape on the Surface. The pointlist argument is
# the vertices of the polygon. The width argument is the thickness to
# draw the outer edge. If width is zero then the polygon will be
# filled.
#
# For aapolygon, use aalines with the 'closed' parameter.
self.fail()
################################################################################
def test_scale__destination( self ):
""" see if the destination surface can be passed in to use.
"""
s = pygame.Surface((32,32))
s2 = pygame.transform.scale(s, (64,64))
s3 = s2.copy()
s3 = pygame.transform.scale(s, (64,64), s3)
pygame.transform.scale(s, (64,64), s2)
# the wrong size surface is past in. Should raise an error.
self.assertRaises(ValueError, pygame.transform.scale, s, (33,64), s3)
if 1:
s = pygame.Surface((32,32))
s2 = pygame.transform.smoothscale(s, (64,64))
s3 = s2.copy()
s3 = pygame.transform.smoothscale(s, (64,64), s3)
pygame.transform.smoothscale(s, (64,64), s2)
# the wrong size surface is past in. Should raise an error.
self.assertRaises(ValueError, pygame.transform.smoothscale, s, (33,64), s3)
def test_average_surfaces__24(self):
SIZE = 32
depth = 24
s1 = pygame.Surface((SIZE, SIZE), 0, depth)
s2 = pygame.Surface((SIZE, SIZE), 0, depth)
s3 = pygame.Surface((SIZE, SIZE), 0, depth)
s1.fill((10,10,70, 255))
s2.fill((10,20,70, 255))
s3.fill((10,130,10, 255))
surfaces = [s1, s2, s3]
sr = pygame.transform.average_surfaces(surfaces)
self.assertEqual( sr.get_masks(), s1.get_masks() )
self.assertEqual( sr.get_flags(), s1.get_flags() )
self.assertEqual( sr.get_losses(), s1.get_losses() )
if 0:
print ( sr, s1 )
print ( sr.get_masks(), s1.get_masks() )
print ( sr.get_flags(), s1.get_flags() )
print ( sr.get_losses(), s1.get_losses() )
print ( sr.get_shifts(), s1.get_shifts() )
self.assertEqual(sr.get_at((0,0)), (10,53,50,255))
def todo_test_chop(self):
# __doc__ (as of 2008-08-02) for pygame.transform.chop:
# pygame.transform.chop(Surface, rect): return Surface
# gets a copy of an image with an interior area removed
#
# Extracts a portion of an image. All vertical and horizontal pixels
# surrounding the given rectangle area are removed. The corner areas
# (diagonal to the rect) are then brought together. (The original
# image is not altered by this operation.)
#
# NOTE: If you want a "crop" that returns the part of an image within
# a rect, you can blit with a rect to a new surface or copy a
# subsurface.
self.fail()
def setUp(self):
self.ag = sprite.AbstractGroup()
self.ag2 = sprite.AbstractGroup()
self.s1 = sprite.Sprite(self.ag)
self.s2 = sprite.Sprite(self.ag2)
self.s3 = sprite.Sprite(self.ag2)
self.s1.image = pygame.Surface((50,10), pygame.SRCALPHA, 32)
self.s2.image = pygame.Surface((10,10), pygame.SRCALPHA, 32)
self.s3.image = pygame.Surface((10,10), pygame.SRCALPHA, 32)
self.s1.rect = self.s1.image.get_rect()
self.s2.rect = self.s2.image.get_rect()
self.s3.rect = self.s3.image.get_rect()
self.s2.rect.move_ip(40, 0)
self.s3.rect.move_ip(100, 100)
def iter_surface_to_array_3d(self, rgba_masks):
dst = pygame.Surface(self.surf_size, 0, 24, masks=rgba_masks)
for surf in self.sources:
dst.fill((0, 0, 0, 0))
src_bitsize = surf.get_bitsize()
view = dst.get_view('3')
self.assertFalse(surf.get_locked())
surface_to_array(view, surf)
self.assertFalse(surf.get_locked())
for posn, i in self.test_points:
sc = surf.get_at(posn)[0:3]
dc = dst.get_at(posn)[0:3]
self.assertEqual(dc, sc,
"%s != %s: flags: %i"
", bpp: %i, posn: %s" %
(dc, sc,
surf.get_flags(), surf.get_bitsize(),
posn))
view = None
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 todo_test_frombuffer(self):
# __doc__ (as of 2008-08-02) for pygame.image.frombuffer:
# pygame.image.frombuffer(string, size, format): return Surface
# create a new Surface that shares data inside a string buffer
#
# Create a new Surface that shares pixel data directly from the string
# buffer. This method takes the same arguments as
# pygame.image.fromstring(), but is unable to vertically flip the
# source data.
#
# This will run much faster than pygame.image.fromstring, since no
# pixel data must be allocated and copied.
self.fail()
def test_from_threshold(self):
""" Does mask.from_threshold() work correctly?
"""
a = [16, 24, 32]
for i in a:
surf = pygame.surface.Surface((70,70), 0, i)
surf.fill((100,50,200),(20,20,20,20))
mask = pygame.mask.from_threshold(surf,(100,50,200,255),(10,10,10,255))
self.assertEqual(mask.count(), 400)
self.assertEqual(mask.get_bounding_rects(), [pygame.Rect((20,20,20,20))])
for i in a:
surf = pygame.surface.Surface((70,70), 0, i)
surf2 = pygame.surface.Surface((70,70), 0, i)
surf.fill((100,100,100))
surf2.fill((150,150,150))
surf2.fill((100,100,100), (40,40,10,10))
mask = pygame.mask.from_threshold(surf, (0,0,0,0), (10,10,10,255), surf2)
self.assertEqual(mask.count(), 100)
self.assertEqual(mask.get_bounding_rects(), [pygame.Rect((40,40,10,10))])
def test_pixel_array (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((10, 20), 0, bpp)
sf.fill ((0, 0, 0))
ar = pygame.PixelArray (sf)
self.assertEqual (ar._pixels_address, sf._pixels_address)
if sf.mustlock ():
self.assertTrue (sf.get_locked ())
self.assertEqual (len (ar), 10)
del ar
if sf.mustlock ():
self.assertFalse (sf.get_locked ())
def test_get_column (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((6, 8), 0, bpp)
sf.fill ((0, 0, 255))
val = sf.map_rgb ((0, 0, 255))
ar = pygame.PixelArray (sf)
ar2 = ar.__getitem__ (1)
self.assertEqual (len(ar2), 8)
self.assertEqual (ar2.__getitem__ (0), val)
self.assertEqual (ar2.__getitem__ (1), val)
self.assertEqual (ar2.__getitem__ (2), val)
ar2 = ar.__getitem__ (-1)
self.assertEqual (len(ar2), 8)
self.assertEqual (ar2.__getitem__ (0), val)
self.assertEqual (ar2.__getitem__ (1), val)
self.assertEqual (ar2.__getitem__ (2), val)
def test_set_pixel (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((10, 20), 0, bpp)
sf.fill ((0, 0, 0))
ar = pygame.PixelArray (sf)
ar.__getitem__ (0).__setitem__ (0, (0, 255, 0))
self.assertEqual (ar[0][0], sf.map_rgb ((0, 255, 0)))
ar.__getitem__ (1).__setitem__ (1, (128, 128, 128))
self.assertEqual (ar[1][1], sf.map_rgb ((128, 128, 128)))
ar.__getitem__(-1).__setitem__ (-1, (128, 128, 128))
self.assertEqual (ar[9][19], sf.map_rgb ((128, 128, 128)))
ar.__getitem__ (-2).__setitem__ (-2, (128, 128, 128))
self.assertEqual (ar[8][-2], sf.map_rgb ((128, 128, 128)))
def test_contains (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((10, 20), 0, bpp)
sf.fill ((0, 0, 0))
sf.set_at ((8, 8), (255, 255, 255))
ar = pygame.PixelArray (sf)
self.assertTrue ((0, 0, 0) in ar)
self.assertTrue ((255, 255, 255) in ar)
self.assertFalse ((255, 255, 0) in ar)
self.assertFalse (0x0000ff in ar)
# Test sliced array
self.assertTrue ((0, 0, 0) in ar[8])
self.assertTrue ((255, 255, 255) in ar[8])
self.assertFalse ((255, 255, 0) in ar[8])
self.assertFalse (0x0000ff in ar[8])
def test_replace (self):
#print "replace start"
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((10, 10), 0, bpp)
sf.fill ((255, 0, 0))
rval = sf.map_rgb ((0, 0, 255))
oval = sf.map_rgb ((255, 0, 0))
ar = pygame.PixelArray (sf)
ar[::2].replace ((255, 0, 0), (0, 0, 255))
self.assertEqual (ar[0][0], rval)
self.assertEqual (ar[1][0], oval)
self.assertEqual (ar[2][3], rval)
self.assertEqual (ar[3][6], oval)
self.assertEqual (ar[8][9], rval)
self.assertEqual (ar[9][9], oval)
ar[::2].replace ((0, 0, 255), (255, 0, 0), weights=(10, 20, 50))
self.assertEqual (ar[0][0], oval)
self.assertEqual (ar[2][3], oval)
self.assertEqual (ar[3][6], oval)
self.assertEqual (ar[8][9], oval)
self.assertEqual (ar[9][9], oval)
#print "replace end"
def test_2dslice_assignment (self):
w = 2 * 5 * 8
h = 3 * 5 * 9
sf = pygame.Surface ((w, h), 0, 32)
ar = pygame.PixelArray (sf)
size = (w, h)
strides = (1, w)
offset = 0
self._test_assignment (sf, ar, size, strides, offset)
xslice = slice (None, None, 2)
yslice = slice (None, None, 3)
ar, size, strides, offset = self._array_slice (
ar, size, (xslice, yslice), strides, offset)
self._test_assignment (sf, ar, size, strides, offset)
xslice = slice (5, None, 5)
yslice = slice (5, None, 5)
ar, size, strides, offset = self._array_slice (
ar, size, (xslice, yslice), strides, offset)
self._test_assignment (sf, ar, size, strides, offset)
def test_shape (self):
for shape in [[4, 16], [5, 13]]:
w, h = shape
sf = pygame.Surface (shape, 0, 32)
ar = pygame.PixelArray (sf)
ai = arrinter.ArrayInterface (ar)
ai_shape = [ai.shape[i] for i in range(ai.nd)]
self.assertEqual (ai_shape, shape)
ar2 = ar[::2,:]
ai2 = arrinter.ArrayInterface (ar2)
w2 = len(([0] * w)[::2])
ai_shape = [ai2.shape[i] for i in range(ai2.nd)]
self.assertEqual (ai_shape, [w2, h])
ar2 = ar[:,::2]
ai2 = arrinter.ArrayInterface (ar2)
h2 = len(([0] * h)[::2])
ai_shape = [ai2.shape[i] for i in range(ai2.nd)]
self.assertEqual (ai_shape, [w, h2])