大小: 30618
备注:
|
大小: 8197
备注:
|
删除的内容标记成这样。 | 加入的内容标记成这样。 |
行号 3: | 行号 3: |
= Surface = | = 绘图 = 除了可以把事先画好的图片blit到Surface上以外,还可以在Surface上自行在Surface上绘制一些简单的图形,比如点、线、方、圆等。这个功能主要由pygame.draw模块完成。 |
行号 5: | 行号 6: |
pygame里的Surface是用来表示图像的对象。Surface有一定的大小和像素格式。如果是8bit像素格式的Surface,它还会用一个调色板映射到24比特颜色。 | 首先导入pygame.draw模块。{{{ import pygame.draw }}}如果已经用了{{{import pygame}}},则pygame.draw模块也被自动导入了。 |
行号 7: | 行号 10: |
调用pygame.Surface可以创建表示图像的新对象。Surface会整个全是黑的。唯一需要指定的参数是大小。如果不指定其他参数,Surface的像素格式会与display Surface的像素格式尽量一致。 | 然后准备好要在上面绘制图形的Surface,比如{{{ surface = pygame.display.set_mode((640, 480)) }}} |
行号 9: | 行号 14: |
像素格式可以通过指定像素深度或者已有的Surface来控制。flag标志位参数是其他一些Surface选项的集合,你可以指定如下的标志 | == 画矩形 == |
行号 11: | 行号 16: |
* HWSURFACE, 在视频内存中创建图像 * SRCALPHA, 像素格式中会包含一个alpha通道 |
接下来就可以在surface上面绘制想要的图形了。比如说画矩形可以使用pygame.draw.rect函数:{{{ pygame.draw.rect(surface, (0,0,255), (100, 200, 100, 100)) }}}第一个参数指定在哪个Surface上画矩形,第二个参数是矩形的颜色,第三个参数是矩形的位置和大小。 |
行号 14: | 行号 20: |
这些参数都仅仅是一个请求,在实际中可能并不能实现。 | 颜色的参数一般是一个由红绿蓝三种颜色值构成的三元组,0是最暗的,255是最亮的。比如(0,0,255)是纯蓝色,(255,0,0)是纯红色,(0,0,0)是黑色,(255,255,255)是白色等等。有时候也可以使用RGBA四元组来表示颜色。如果Surface包含alpha,四元组中alpha值会被直接写入到Surface里面,画图函数并不会进行透明的绘画。颜色参数也可以是一个整数,是映射到Surface里的像素值。其他绘图函数里面的颜色参数也是一样的。 |
行号 16: | 行号 22: |
Advance users can combine a set of bitmasks with a depth value. The masks are a set of 4 integers representing which bits in a pixel will represent each color. Normal Surfaces should not require the masks argument. | 矩形参数由四个值构成的元组,分别是矩形左上角的x、y坐标,矩形的宽和高。 |
行号 18: | 行号 24: |
Surfaces can have many extra attributes like alpha planes, colorkeys, source rectangle clipping. These functions mainly effect how the Surface is blitted to other Surfaces. The blit routines will attempt to use hardware acceleratio | 默认情况下,画出来的矩形是实心的(中间填充了指定的颜色)。如果要画一个只有边框的矩形,可以指定一个可选的参数width。比如{{{ pygame.draw.rect(surface, (0,0,255), (100, 200, 100, 100), 2) }}}可以在屏幕上画一个边框是2个像素粗的矩形,中间是透明的。如果不指定这个width参数,或者width指定为0,则画出来的矩形就是实心的。其他有些绘图函数里面也有类似的参数,功能也是相似的。 |
行号 20: | 行号 28: |
when possible, otherwise will use highly optimized software blitting methods. | pygame.draw.rect函数返回一个矩形,表示屏幕上被修改的像素的区域范围。其它绘图函数也都有这样的返回值。 |
行号 22: | 行号 30: |
There are three types of transparency supported in Pygame: colorkeys, surface alphas, and pixel alphas. Surface alphas can be mixed with colorkeys, but an image with per pixel alphas cannot use the other modes. Colorkey transparency makes a single color value transparent. Any pixels matching the colorkey will not be drawn. The surface alpha value is a single value that changes the transparency for the entire image. A surface alpha of 255 is opaque, and a value of 0 is completely transparent. | == 画多边形 == |
行号 24: | 行号 32: |
Per pixel alphas are different because they store a transparency value for every pixel. This allows for the most precise transparency effects, but it also the slowest. Per pixel alphas cannot be mixed with surface alpha and colorkeys. | 用pygame.draw.polygon可以在Surface上画一个多边形。比如{{{ pygame.draw.polygon(surface, (255,0,0), [(100, 100),(200, 100),(250,186.6),(200,273.2),(100, 273.2),(50,186.6)]) }}} 第三个参数pointlist参数是多边形顶点的列表。可选的第四个width参数是多边形的边的粗细。如果width是0或者被忽略,多边形是被填充的。{{{ pygame.draw.polygon(surface, (0,255,0), [(100, 100),(200, 100),(250,186.6),(200,273.2),(100, 273.2),(50,186.6)],1) }}} |
行号 26: | 行号 39: |
There is support for pixel access for the Surfaces. Pixel access on hardware surfaces is slow and not recommended. Pixels can be accessed using the get_at() and set_at() functions. These methods are fine for simple access, but will be considerably slow when doing of pixel work with them. If you plan on doing a lot of pixel level work, it is recommended to use the pygame.surfarray module, which can treat the surfaces like large multidimensional arrays (and it's quite quick). | == 画圆 == |
行号 28: | 行号 41: |
Any functions that directly access a surface's pixel data will need that surface to be lock()'ed. These functions can lock() and unlock() the surfaces themselves without assistance. But, if a function will be called many times, there will be a lot of overhead for multiple locking and unlocking of the surface. It is best to lock the surface manually before making the function call many times, and then unlocking when you are finished. All functions that need a locked surface will say so in their docs. Remember to leave the Surface locked only while necessary. | pygame.draw.circle在Surface上画一个圆形。{{{ pygame.draw.circle(surface, (255,255,0), (100, 100), 50) }}}第三个参数pos是圆的圆心,第四个参数radius是半径大小。可选的第五个参数width是圆边的粗细,如果width缺省或者是0圆会被填充。 |
行号 30: | 行号 45: |
Surface pixels are stored internally as a single number that has all the colors encoded into it. Use the Surface.map_rgb - convert a color into a mapped color value and Surface.unmap_rgb - convert a mapped integer color value into a Color to convert between individual red, green, and blue values into a packed integer for that Surface. | == 画椭圆 == |
行号 32: | 行号 47: |
Surfaces can also reference sections of other Surfaces. These are created with the Surface.subsurface - create a new surface that references its parent method. Any change to either Surface will effect the other. | pygame.draw.ellipse在矩形区域中画一个椭圆的形状。比如{{{ pygame.draw.ellipse(surface, (0,255,255), (200, 200, 200, 100)) }}}第三个参数指定的矩形区域是椭圆填充的区域。可选的第四个参数width是边的粗细。如果width缺省或者是0,椭圆会被填充。 |
行号 34: | 行号 51: |
Each Surface contains a clipping area. By default the clip area covers the entire Surface. If it is changed, all drawing operations will only effect the smaller area. | == 画弧线 == |
行号 36: | 行号 53: |
== Surface.blit == | pygame.draw.arc画椭圆的一段。比如{{{ pygame.draw.arc(surface, (0,255,0), (200, 200, 200, 100), 3.14159/3, 3.14159*2/3) }}} 在Surface上画一个椭圆状的弧线。第三个参数rect指定椭圆填充的矩形。接下来两个角度参数指定起始和终止的角度(以弧度为单位),朝右为0度。可选的第六个参数width是弧线的粗细,默认值是1。 |
行号 38: | 行号 58: |
draw one image onto another Surface.blit(source, dest, area=None, special_flags = 0): return Rect Draws a source Surface onto this Surface. The draw can be positioned with the dest argument. Dest can either be pair of coordinates representing the upper left corner of the source. A Rect can also be passed as the destination and the topleft corner of the rectangle will be used as the position for the blit. The size of the destination rectangle does not effect the blit. An optional area rectangle can be passed as well. This represents a smaller portion of the source Surface to draw. An optional special flags is for passing in BLEND_ADD, BLEND_SUB, BLEND_MULT, BLEND_MIN, BLEND_MAX With other special blitting flags perhaps added in the future. The return rectangle is the area of the affected pixels, excluding any pixels outside the destination Surface, or outside the clipping area. Pixel alphas will be ignored when blitting to an 8 bit Surface. special_flags new in pygame 1.8. == Surface.convert == change the pixel format of an image Surface.convert(Surface): return Surface Surface.convert(depth, flags=0): return Surface Surface.convert(masks, flags=0): return Surface Surface.convert(): return Surface Creates a new copy of the Surface with the pixel format changed. The new pixel format can be determined from another existing Surface. Otherwise depth, flags, and masks arguments can be used, similar to the pygame.Surface - pygame object for representing images call. If no arguments are passed the new Surface will have the same pixel format as the display Surface. This is always the fastest format for blitting. It is a good idea to convert all Surfaces before they are blitted many times. The converted Surface will have no pixel alphas. They will be stripped if the original had them. See Surface.convert_alpha - change the pixel format of an image including per pixel alphas for preserving or creating per-pixel alphas. == Surface.copy == create a new copy of a Surface Surface.copy(): return Surface Makes a duplicate copy of a Surface. The new Surface will have the same pixel formats, color palettes, and transparency settings as the original. == Surface.fill == fill Surface with a solid color Surface.fill(color, rect=None): return Rect Fill the Surface with a solid color. If no rect argument is given the entire Surface will be filled. The rect argument will limit the fill to a specific area. The fill will also be contained by the Surface clip area. The color argument can be either an RGB sequence or a mapped color index. This will return the affected Surface area. == Surface.set_colorkey == Set the transparent colorkey Surface.set_colorkey(Color, flags=0): return None Surface.set_colorkey(None): return None Set the current color key for the Surface. When blitting this Surface onto a destination, and pixels that have the same color as the colorkey will be transparent. The color can be an RGB color or a mapped color integer. If None is passed, the colorkey will be unset. The colorkey will be ignored if the Surface is formatted to use per pixel alpha values. The colorkey can be mixed with the full Surface alpha value. The optional flags argument can be set to pygame.RLEACCEL to provide better performance on non accelerated displays. An RLEACCEL Surface will be slower to modify, but quicker to blit as a source. |
== 画线段 == pygame.draw.line函数可以画一条直线段。比如{{{ pygame.draw.line(surface, (255,0,255), (100, 100), (200, 200)) }}}第三个参数指定起点,第四个参数指定终点。可选的第五个参数width指定线的宽度,默认是1。线段终点没有箭头,宽的线段终点是方形的。 |
行号 99: | 行号 64: |
== Surface.get_at == | == 画连续的线段 == pygame.draw.lines画多条连续的线段。比如{{{ pygame.draw.lines(surface, (255,255,255), False, [(100, 100), (200, 200), (300, 200), (200, 100)]) }}}第四个参数pointlist是一系列点的列表。如果第三个参数是True,则在最后一点和第一点之间会画一条线段。可选的第五个参数表示线的宽度,默认为1。这个函数不会画终点箭头和中间连接头。线段有尖锐的拐角,粗的线段会有不太好看的拐角。 |
行号 101: | 行号 69: |
get the color value at a single pixel Surface.get_at((x, y)): return Color |
== 抗锯齿的线段 == pygame.draw.aaline画抗锯齿的线段。{{{ pygame.draw.aaline(surface, (255,255,0), (200, 100), (300, 200)) }}}这个函数的用法和画线段的函数差不多,只是画出来的线段有抗锯齿效果,看上去比较光滑。有一个可选的第五个参数blend,如果blend是True,则阴影部分是和原始像素混合而不是直接覆盖的。这个函数接受浮点数作为点的坐标。 |
行号 104: | 行号 74: |
Return the RGBA color value at the given pixel. If the Surface has no per pixel alpha, then the alpha value will always be 255 (opaque). If the pixel position is outside the area of the Surface an IndexError exception will be raised. | pygame.draw.aalines可以画多条连续的抗锯齿线段。{{{ pygame.draw.aalines(surface, (0,0, 255), False, [(100, 100), (200, 200), (300, 100), (200, 0)]) }}}如果第三个参数如果是True,则在第一个点和最后一点之间会画一条直线。有一个可选的第五个参数blend,如果blend参数是True,则阴影部分是和原始像素混合而不是直接覆盖的。这个函数接受浮点数作为点的坐标。 |
行号 106: | 行号 78: |
Getting and setting pixels one at a time is generally too slow to be used in a game or realtime situation. | == 点操作 == 画点的方法和其它方法不太一样,用Surface.set_at方法完成画点的操作,比如:{{{ surface.set_at((100, 100), (255,255,255)) }}}第一个参数是点的坐标,第二个参数是颜色。在游戏和实时模拟中,一次取得和设置一个像素是很慢的。 |
行号 108: | 行号 83: |
This function will temporarily lock and unlock the Surface as needed. |
除了可以在Surface上画点,还可以用Surface.get_at读取Surface上像素的值。比如{{{ color = surface.get_at((100, 100)) }}}这个函数返回给定点的颜色值。 |
行号 111: | 行号 87: |
== Surface.set_at == | == 填充区域 == Surface.fill方法可以用一种颜色填充一个矩形区域。比如{{{ surface.fill((255,0,0), (100, 200, 100, 100)) }}}第一个参数指定要填充的颜色,第二个参数指定填充的矩形区域。如果没有给定第二个参数,整个Surface会被填充。第二个参数会限制备填充的区域。这个函数会返回受影响的Surface区域。 |
行号 113: | 行号 92: |
set the color value for a single pixel Surface.set_at((x, y), Color): return None |
= 写字 = |
行号 116: | 行号 94: |
Set the RGBA or mapped integer color value for a single pixel. If the Surface does not have per pixel alphas, the alpha value is ignored. Settting pixels outside the Surface area or outside the Surface clipping will have no effect. | 相对于在Surface上画图,在Surface上写文字要复杂得多。 |
行号 118: | 行号 96: |
Getting and setting pixels one at a time is generally too slow to be used in a game or realtime situation. | 首先需要导入pygame.font模块并初始化。{{{ import pygame.font pygame.font.init() }}} |
行号 120: | 行号 101: |
This function will temporarily lock and unlock the Surface as needed. | == 选择字体 == |
行号 122: | 行号 103: |
== Surface.set_clip == | 然后用pygame.font.get_fonts获取可用的字体的列表。{{{ pygame.font.get_fonts() }}}它返回一个字体名字的列表。 |
行号 124: | 行号 107: |
set the current clipping area of the Surface Surface.set_clip(rect): return None Surface.set_clip(None): return None |
然后再用字体名字列表中的一个名字可以创建一个字体对象。{{{ font = pygame.font.SysFont("monospace", 12) }}}第一个参数指定字体的名字,第二个参数指定字体的大小。可选的第三个参数bold指定是否粗体,默认不是粗题。可选的地四个参数italic指定是否斜体,默认不是斜体。 |
行号 128: | 行号 111: |
Each Surface has an active clipping area. This is a rectangle that represents the only pixels on the Surface that can be modified. If None is passed for the rectangle the full Surface will be available for changes. | 如果是要使用自己给的字体文件,可以这样创建字体对象{{{ font = pygame.font.Font("/usr/share/fonts/truetype/arphic/uming.ttf", 12) }}}第一个参数指定要载入的字体文件的完整路径,第二个参数指定字体的大小。 |
行号 130: | 行号 115: |
The clipping area is always restricted to the area of the Surface itself. If the clip rectangle is too large it will be shrunk to fit inside the Surface. |
== 创建文字Surface == 使用字体对象的Font.render函数可以创建一个Surface,里面包含写出来的文字。比如{{{ font_surface = font.render("Hello world!", False, (255,0,0)) }}}第一个参数是要写的文字,文字只能包含一行,换行符不会被画出来。第二个参数指定是否使用抗锯齿效果,如果是True字符会有光滑的边缘。第三个参数是字体的颜色。可选的第四个参数background用来指定文字背景的颜色。如果没有指定background,背景是透明的。返回创建的Surface,它上面包含了画出来的文字,它的大小是能容纳这些字的最小的大小。 |
行号 133: | 行号 120: |
== Surface.get_clip == get the current clipping are of the Surface Surface.get_clip(): return Rect Return a rectangle of the current clipping area. The Surface will always return a valid rectangle that will never be outside the bounds of the image. If the Surface has had None set for the clipping area, the Surface will return a rectangle with the full area of the Surface. == Surface.get_size == get the dimensions of the Surface Surface.get_size(): return (width, height) Return the width and height of the Surface in pixels. == Surface.get_width == get the width of the Surface Surface.get_width(): return width Return the width of the Surface in pixels. == Surface.get_height == get the height of the Surface Surface.get_height(): return height Return the height of the Surface in pixels. = image = The image module contains functions for loading and saving pictures, as well as transferring Surfaces to formats usable by other packages. Note that there is no Image class; an image is loaded as a Surface object. The Surface class allows manipulation (drawing lines, setting pixels, capturing regions, etc.). The image module is a required dependency of Pygame, but it only optionally supports any extended file formats. By default it can only load uncompressed BMP images. When built with full image support, the pygame.image.load - load new image from a file function can support the following formats. * JPG * PNG * GIF (non animated) * BMP * PCX * TGA (uncompressed) * TIF * LBM (and PBM) * PBM (and PGM, PPM) * XPM Saving images only supports a limited set of formats. You can save to the following formats. * BMP * TGA * PNG * JPEG PNG, JPEG saving new in pygame 1.8. == pygame.image.load == load new image from a file pygame.image.load(filename): return Surface pygame.image.load(fileobj, namehint=""): return Surface Load an image from a file source. You can pass either a filename or a Python file-like object. Pygame will automatically determine the image type (e.g., GIF or bitmap) and create a new Surface object from the data. In some cases it will need to know the file extension (e.g., GIF images should end in ".gif"). If you pass a raw file-like object, you may also want to pass the original filename as the namehint argument. The returned Surface will contain the same color format, colorkey and alpha transparency as the file it came from. You will often want to call Surface.convert - change the pixel format of an image with no arguments, to create a copy that will draw more quickly on the screen. For alpha transparency, like in .png images use the convert_alpha() method after loading so that the image has per pixel transparency. Pygame may not always be built to support all image formats. At minimum it will support uncompressed BMP. If pygame.image.get_extended - test if extended image formats can be loaded returns 'True', you should be able to load most images( including png, jpg and gif ). You should use os.path.join() for compatibility. eg. asurf = pygame.image.load(os.path.join('data', 'bla.png')) == pygame.image.save == save an image to disk pygame.image.save(Surface, filename): return None This will save your Surface as either a BMP, TGA, PNG, or JPEG image. If the filename extension is unrecognized it will default to TGA. Both TGA, and BMP file formats create uncompressed files. PNG, JPEG saving new in pygame 1.8. == pygame.image.tostring == transfer image to string buffer pygame.image.tostring(Surface, format, flipped=False): return string Creates a string that can be transferred with the 'fromstring' method in other Python imaging packages. Some Python image packages prefer their images in bottom-to-top format (PyOpenGL for example). If you pass True for the flipped argument, the string buffer will be vertically flipped. The format argument is a string of one of the following values. Note that only 8bit Surfaces can use the "P" format. The other formats will work for any Surface. Also note that other Python image packages support more formats than Pygame. o P, 8bit palettized Surfaces o RGB, 24bit image o RGBX, 32bit image with unused space o RGBA, 32bit image with an alpha channel o ARGB, 32bit image with alpha channel first == pygame.image.fromstring == create new Surface from a string buffer pygame.image.fromstring(string, size, format, flipped=False): return Surface This function takes arguments similar to pygame.image.tostring - transfer image to string buffer. The size argument is a pair of numbers representing the width and height. Once the new Surface is created you can destroy the string buffer. The size and format image must compute the exact same size as the passed string buffer. Otherwise an exception will be raised. See the pygame.image.frombuffer - create a new Surface that shares data inside a string buffer method for a potentially faster way to transfer images into Pygame. = draw = Draw several simple shapes to a Surface. These functions will work for rendering to any format of Surface. Rendering to hardware Surfaces will be slower than regular software Surfaces. Most of the functions take a width argument to represent the size of stroke around the edge of the shape. If a width of 0 is passed the function will actually solid fill the entire shape. All the drawing functions respect the clip area for the Surface, and will be constrained to that area. The functions return a rectangle representing the bounding area of changed pixels. Most of the arguments accept a color argument that is an RGB triplet. These can also accept an RGBA quadruplet. The alpha value will be written directly into the Surface if it contains pixel alphas, but the draw function will not draw transparently. The color argument can also be an integer pixel value that is already mapped to the Surface's pixel format. These functions must temporarily lock the Surface they are operating on. Many sequential drawing calls can be sped up by locking and unlocking the Surface object around the draw calls. == pygame.draw.rect == draw a rectangle shape pygame.draw.rect(Surface, color, Rect, width=0): return Rect Draws a rectangular shape on the Surface. The given Rect is the area of the rectangle. The width argument is the thickness to draw the outer edge. If width is zero then the rectangle will be filled. Keep in mind the Surface.fill - fill Surface with a solid color method works just as well for drawing filled rectangles. In fact the Surface.fill - fill Surface with a solid color can be hardware accelerated on some platforms with both software and hardware display modes. == pygame.draw.polygon == draw a shape with any number of sides pygame.draw.polygon(Surface, color, pointlist, width=0): return Rect 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. == pygame.draw.circle == draw a circle around a point pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect Draws a circular shape on the Surface. The pos argument is the center of the circle, and radius is the size. The width argument is the thickness to draw the outer edge. If width is zero then the circle will be filled. == pygame.draw.ellipse == draw a round shape inside a rectangle pygame.draw.ellipse(Surface, color, Rect, width=0): return Rect Draws an elliptical shape on the Surface. The given rectangle is the area that the circle will fill. The width argument is the thickness to draw the outer edge. If width is zero then the ellipse will be filled. == pygame.draw.arc == draw a partial section of an ellipse pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, width=1): return Rect 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. == pygame.draw.line == draw a straight line segment pygame.draw.line(Surface, color, start_pos, end_pos, width=1): return Rect Draw a straight line segment on a Surface. There are no endcaps, the ends are squared off for thick lines. == pygame.draw.lines == draw multiple contiguous line segments pygame.draw.lines(Surface, color, closed, pointlist, width=1): return Rect 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. == pygame.draw.aaline == draw fine antialiased lines pygame.draw.aaline(Surface, color, startpos, endpos, blend=1): return Rect Draws an anti-aliased line on a surface. This will respect the clipping rectangle. A bounding box of the affected area is returned returned as a rectangle. If blend is true, the shades will be be blended with existing pixel shades instead of overwriting them. This function accepts floating point values for the end points. == pygame.draw.aalines == pygame.draw.aalines(Surface, color, closed, pointlist, blend=1): return Rect Draws a sequence on a surface. You must pass at least two points in the sequence of points. The closed argument is a simple boolean and if true, a line will be draw between the first and last points. The boolean blend argument set to true will blend the shades with existing shades instead of overwriting them. This function accepts floating point values for the end points. = font = The font module allows for rendering TrueType fonts into a new Surface object. This module is optional and requires SDL_ttf as a dependency. You should test that pygame.font is available and initialized before attempting to use the module. Most of the work done with fonts are done by using the actual Font objects. The module by itself only has routines to initialize the module and create Font objects with pygame.font.Font - create a new Font object from a file. You can load fonts from the system by using the pygame.font.SysFont - create a Font object from the system fonts function. There are a few other functions to help lookup the system fonts. Pygame comes with a builtin default font. This can always be accessed by passing None as the font name. == pygame.font.init == initialize the font module pygame.font.init(): return None This method is called automatically by pygame.init - initialize all imported pygame modules. It initializes the font module. The module must be initialized before any other functions will work. It is safe to call this function more than once. == pygame.font.quit == uninitialize the font module pygame.font.quit(): return None Manually uninitialize SDL_ttf's font system. This is called automatically by pygame.quit - uninitialize all pygame modules. It is safe to call this function even if font is currently not initialized. == pygame.font.get_init == true if the font module is initialized pygame.font.get_init(): return bool Test if the font module is initialized or not. == pygame.font.get_default_font == get the filename of the default font pygame.font.get_default_font(): return string Return the filename of the system font. This is not the full path to the file. This file can usually be found in the same directory as the font module, but it can also be bundled in separate archives. == pygame.font.get_fonts == get all available fonts pygame.font.get_fonts(): return list of strings Returns a list of all the fonts available on the system. The names of the fonts will be set to lowercase with all spaces and punctuation removed. This works on most systems, but some will return an empty list if they cannot find fonts. == pygame.font.match_font == find a specific font on the system pygame.font.match_font(name, bold=False, italic=False): return path Returns the full path to a font file on the system. If bold or italic are set to true, this will attempt to find the correct family of font. The font name can actually be a comma separated list of font names to try. If none of the given names are found, None is returned. Example: print pygame.font.match_font('bitstreamverasans') # output is: /usr/share/fonts/truetype/ttf-bitstream-vera/Vera.ttf # (but only if you have Vera on your system) == pygame.font.SysFont == create a Font object from the system fonts pygame.font.SysFont(name, size, bold=False, italic=False): return Font Return a new Font object that is loaded from the system fonts. The font will match the requested bold and italic flags. If a suitable system font is not found this will fallback on loading the default pygame font. The font name can be a comma separated list of font names to look for. == pygame.font.Font == create a new Font object from a file pygame.font.Font(filename, size): return Font pygame.font.Font(object, size): return Font Font.render - draw text on a new Surface draw text on a new Surface Font.size - determine the amount of space needed to render text determine the amount of space needed to render text Font.set_underline - control if text is rendered with an underline control if text is rendered with an underline Font.get_underline - check if text will be rendered with an underline check if text will be rendered with an underline Font.set_bold - enable fake rendering of bold text enable fake rendering of bold text Font.get_bold - check if text will be rendered bold check if text will be rendered bold Font.set_italic - enable fake rendering of italic text enable fake rendering of italic text Font.get_italic - check if the text will be rendered italic check if the text will be rendered italic Font.get_linesize - get the line space of the font text get the line space of the font text Font.get_height - get the height of the font get the height of the font Font.get_ascent - get the ascent of the font get the ascent of the font Font.get_descent - get the descent of the font get the descent of the font Load a new font from a given filename or a python file object. The size is the height of the font in pixels. If the filename is None the Pygame default font will be loaded. If a font cannot be loaded from the arguments given an exception will be raised. Once the font is created the size cannot be changed. Font objects are mainly used to render text into new Surface objects. The render can emulate bold or italic features, but it is better to load from a font with actual italic or bold glyphs. The rendered text can be regular strings or unicode. === Font.render === draw text on a new Surface Font.render(text, antialias, color, background=None): return Surface This creates a new Surface with the specified text rendered on it. Pygame provides no way to directly draw text on an existing Surface: instead you must use Font.render - draw text on a new Surface to create an image (Surface) of the text, then blit this image onto another Surface. The text can only be a single line: newline characters are not rendered. The antialias argument is a boolean: if true the characters will have smooth edges. The color argument is the color of the text [e.g.: (0,0,255) for blue]. The optional background argument is a color to use for the text background. If no background is passed the area outside the text will be transparent. The Surface returned will be of the dimensions required to hold the text. (the same as those returned by Font.size()). If an empty string is passed for the text, a blank surface will be returned that is one pixel wide and the height of the font. Depending on the type of background and antialiasing used, this returns different types of Surfaces. For performance reasons, it is good to know what type of image will be used. If antialiasing is not used, the return image will always be an 8bit image with a two color palette. If the background is transparent a colorkey will be set. Antialiased images are rendered to 24-bit RGB images. If the background is transparent a pixel alpha will be included. Optimization: if you know that the final destination for the text (on the screen) will always have a solid background, and the text is antialiased, you can improve performance by specifying the background color. This will cause the resulting image to maintain transparency information by colorkey rather than (much less efficient) alpha values. If you render '\n' a unknown char will be rendered. Usually a rectangle. Instead you need to handle new lines yourself. Font rendering is not thread safe: only a single thread can render text any time. === Font.size === determine the amount of space needed to render text Font.size(text): return (width, height) Returns the dimensions needed to render the text. This can be used to help determine the positioning needed for text before it is rendered. It can also be used for wordwrapping and other layout effects. Be aware that most fonts use kerning which adjusts the widths for specific letter pairs. For example, the width for "ae" will not always match the width for "a" + "e". === Font.set_underline === control if text is rendered with an underline Font.set_underline(bool): return None When enabled, all rendered fonts will include an underline. The underline is always one pixel thick, regardless of font size. This can be mixed with the bold and italic modes. === Font.get_underline === check if text will be rendered with an underline Font.get_underline(): return bool Return True when the font underline is enabled. === Font.set_bold === enable fake rendering of bold text Font.set_bold(bool): return None Enables the bold rendering of text. This is a fake stretching of the font that doesn't look good on many font types. If possible load the font from a real bold font file. While bold, the font will have a different width than when normal. This can be mixed with the italic and underline modes. === Font.get_bold === check if text will be rendered bold Font.get_bold(): return bool Return True when the font bold rendering mode is enabled. === Font.set_italic === enable fake rendering of italic text Font.set_bold(bool): return None Enables fake rendering of italic text. This is a fake skewing of the font that doesn't look good on many font types. If possible load the font from a real italic font file. While italic the font will have a different width than when normal. This can be mixed with the bold and underline modes. === Font.get_italic === check if the text will be rendered italic Font.get_italic(): return bool Return True when the font italic rendering mode is enabled. === Font.get_linesize === get the line space of the font text Font.get_linesize(): return int Return the height in pixels for a line of text with the font. When rendering multiple lines of text this is the recommended amount of space between lines. === Font.get_height === get the height of the font Font.get_height(): return int Return the height in pixels of the actual rendered text. This is the average size for each glyph in the font. === Font.get_ascent === get the ascent of the font Font.get_ascent(): return int Return the height in pixels for the font ascent. The ascent is the number of pixels from the font baseline to the top of the font. === Font.get_descent === get the descent of the font Font.get_descent(): return int Return the height in pixels for the font descent. The descent is the number of pixels from the font baseline to the bottom of the font. |
要在已有的Surface上写字,只能先创建一个只包含文字的Surface,然后把它blit到已有的Surface上。比如:{{{ surface.blit(font_surface, (100, 100)) }}} |
绘图
除了可以把事先画好的图片blit到Surface上以外,还可以在Surface上自行在Surface上绘制一些简单的图形,比如点、线、方、圆等。这个功能主要由pygame.draw模块完成。
首先导入pygame.draw模块。
import pygame.draw
如果已经用了import pygame,则pygame.draw模块也被自动导入了。
然后准备好要在上面绘制图形的Surface,比如
surface = pygame.display.set_mode((640, 480))
1. 画矩形
接下来就可以在surface上面绘制想要的图形了。比如说画矩形可以使用pygame.draw.rect函数:
pygame.draw.rect(surface, (0,0,255), (100, 200, 100, 100))
第一个参数指定在哪个Surface上画矩形,第二个参数是矩形的颜色,第三个参数是矩形的位置和大小。
颜色的参数一般是一个由红绿蓝三种颜色值构成的三元组,0是最暗的,255是最亮的。比如(0,0,255)是纯蓝色,(255,0,0)是纯红色,(0,0,0)是黑色,(255,255,255)是白色等等。有时候也可以使用RGBA四元组来表示颜色。如果Surface包含alpha,四元组中alpha值会被直接写入到Surface里面,画图函数并不会进行透明的绘画。颜色参数也可以是一个整数,是映射到Surface里的像素值。其他绘图函数里面的颜色参数也是一样的。
矩形参数由四个值构成的元组,分别是矩形左上角的x、y坐标,矩形的宽和高。
默认情况下,画出来的矩形是实心的(中间填充了指定的颜色)。如果要画一个只有边框的矩形,可以指定一个可选的参数width。比如
pygame.draw.rect(surface, (0,0,255), (100, 200, 100, 100), 2)
可以在屏幕上画一个边框是2个像素粗的矩形,中间是透明的。如果不指定这个width参数,或者width指定为0,则画出来的矩形就是实心的。其他有些绘图函数里面也有类似的参数,功能也是相似的。
pygame.draw.rect函数返回一个矩形,表示屏幕上被修改的像素的区域范围。其它绘图函数也都有这样的返回值。
2. 画多边形
用pygame.draw.polygon可以在Surface上画一个多边形。比如
pygame.draw.polygon(surface, (255,0,0), [(100, 100),(200, 100),(250,186.6),(200,273.2),(100, 273.2),(50,186.6)])
第三个参数pointlist参数是多边形顶点的列表。可选的第四个width参数是多边形的边的粗细。如果width是0或者被忽略,多边形是被填充的。
pygame.draw.polygon(surface, (0,255,0), [(100, 100),(200, 100),(250,186.6),(200,273.2),(100, 273.2),(50,186.6)],1)
3. 画圆
pygame.draw.circle在Surface上画一个圆形。
pygame.draw.circle(surface, (255,255,0), (100, 100), 50)
第三个参数pos是圆的圆心,第四个参数radius是半径大小。可选的第五个参数width是圆边的粗细,如果width缺省或者是0圆会被填充。
4. 画椭圆
pygame.draw.ellipse在矩形区域中画一个椭圆的形状。比如
pygame.draw.ellipse(surface, (0,255,255), (200, 200, 200, 100))
第三个参数指定的矩形区域是椭圆填充的区域。可选的第四个参数width是边的粗细。如果width缺省或者是0,椭圆会被填充。
5. 画弧线
pygame.draw.arc画椭圆的一段。比如
pygame.draw.arc(surface, (0,255,0), (200, 200, 200, 100), 3.14159/3, 3.14159*2/3)
在Surface上画一个椭圆状的弧线。第三个参数rect指定椭圆填充的矩形。接下来两个角度参数指定起始和终止的角度(以弧度为单位),朝右为0度。可选的第六个参数width是弧线的粗细,默认值是1。
== 画线段 == pygame.draw.line函数可以画一条直线段。比如
pygame.draw.line(surface, (255,0,255), (100, 100), (200, 200))
第三个参数指定起点,第四个参数指定终点。可选的第五个参数width指定线的宽度,默认是1。线段终点没有箭头,宽的线段终点是方形的。
6. 画连续的线段
pygame.draw.lines画多条连续的线段。比如
pygame.draw.lines(surface, (255,255,255), False, [(100, 100), (200, 200), (300, 200), (200, 100)])
第四个参数pointlist是一系列点的列表。如果第三个参数是True,则在最后一点和第一点之间会画一条线段。可选的第五个参数表示线的宽度,默认为1。这个函数不会画终点箭头和中间连接头。线段有尖锐的拐角,粗的线段会有不太好看的拐角。
7. 抗锯齿的线段
pygame.draw.aaline画抗锯齿的线段。
pygame.draw.aaline(surface, (255,255,0), (200, 100), (300, 200))
这个函数的用法和画线段的函数差不多,只是画出来的线段有抗锯齿效果,看上去比较光滑。有一个可选的第五个参数blend,如果blend是True,则阴影部分是和原始像素混合而不是直接覆盖的。这个函数接受浮点数作为点的坐标。
pygame.draw.aalines可以画多条连续的抗锯齿线段。
pygame.draw.aalines(surface, (0,0, 255), False, [(100, 100), (200, 200), (300, 100), (200, 0)])
如果第三个参数如果是True,则在第一个点和最后一点之间会画一条直线。有一个可选的第五个参数blend,如果blend参数是True,则阴影部分是和原始像素混合而不是直接覆盖的。这个函数接受浮点数作为点的坐标。
8. 点操作
画点的方法和其它方法不太一样,用Surface.set_at方法完成画点的操作,比如:
surface.set_at((100, 100), (255,255,255))
第一个参数是点的坐标,第二个参数是颜色。在游戏和实时模拟中,一次取得和设置一个像素是很慢的。
除了可以在Surface上画点,还可以用Surface.get_at读取Surface上像素的值。比如
color = surface.get_at((100, 100))
这个函数返回给定点的颜色值。
9. 填充区域
Surface.fill方法可以用一种颜色填充一个矩形区域。比如
surface.fill((255,0,0), (100, 200, 100, 100))
第一个参数指定要填充的颜色,第二个参数指定填充的矩形区域。如果没有给定第二个参数,整个Surface会被填充。第二个参数会限制备填充的区域。这个函数会返回受影响的Surface区域。
写字
相对于在Surface上画图,在Surface上写文字要复杂得多。
首先需要导入pygame.font模块并初始化。
import pygame.font pygame.font.init()
1. 选择字体
然后用pygame.font.get_fonts获取可用的字体的列表。
pygame.font.get_fonts()
它返回一个字体名字的列表。
然后再用字体名字列表中的一个名字可以创建一个字体对象。
font = pygame.font.SysFont("monospace", 12)
第一个参数指定字体的名字,第二个参数指定字体的大小。可选的第三个参数bold指定是否粗体,默认不是粗题。可选的地四个参数italic指定是否斜体,默认不是斜体。
如果是要使用自己给的字体文件,可以这样创建字体对象
font = pygame.font.Font("/usr/share/fonts/truetype/arphic/uming.ttf", 12)
第一个参数指定要载入的字体文件的完整路径,第二个参数指定字体的大小。
2. 创建文字Surface
使用字体对象的Font.render函数可以创建一个Surface,里面包含写出来的文字。比如
font_surface = font.render("Hello world!", False, (255,0,0))
第一个参数是要写的文字,文字只能包含一行,换行符不会被画出来。第二个参数指定是否使用抗锯齿效果,如果是True字符会有光滑的边缘。第三个参数是字体的颜色。可选的第四个参数background用来指定文字背景的颜色。如果没有指定background,背景是透明的。返回创建的Surface,它上面包含了画出来的文字,它的大小是能容纳这些字的最小的大小。
要在已有的Surface上写字,只能先创建一个只包含文字的Surface,然后把它blit到已有的Surface上。比如:
surface.blit(font_surface, (100, 100))