Pygame中的convert()

convert()

还是从案例开始:

import pygame
from pygame.locals import *

def main():
    # 初始化
    pygame.init()
    screen = pygame.display.set_mode((200, 100))
    pygame.display.set_caption('Basic Pygame program')

    # 填充背景
    background = pygame.Surface(screen.get_size())
    background = background.convert()  
    background.fill((250, 250, 250))  # RGB

    # 创建文本文本
    font = pygame.font.Font(None, 36)
    text = font.render("Hello There", 1, (10, 10, 10))

    # 设置字体要放置的矩形框的位置
    textpos = text.get_rect()
    textpos.centerx = background.get_rect().centerx
    textpos.centery = background.get_rect().centery

    # 绘制文本到指定位置,画布对象是backgorund, 位置(centerx, centery)
    background.blit(text, textpos)

    # 绘制画布对象background到窗口screen,位置(0,0)
    screen.blit(background, (0, 0))
    pygame.display.flip()

    # 循环,使窗口一直存在,直到发生退出事件
    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return

main()

上面用到了convert()这个方法,这里解释:
直面意思:转变,转换,转化
这里转化的是“像素格式”。这是指surface在特定像素中记录各个颜色的特定方式。
如果surface格式与显示格式不同,则SDL将不得不在每次转换时即时对其进行转换,这是一个非常耗时的过程。
故而在加载图像的时候,应该注意这一点, 不仅仅是这样做:

surface = pygame.image.load('foo.png')

而应该:

surface = pygame.image.load('foo.png').convert()

也就是convert()的加入是为了渲染的速度的考虑。那什么又是我们前面提到的surface?

什么又是surface

pygame中最重要的一部分。可以将surface理解为一张空白的纸,也就是一张画布。而且大小任意。

  1. 使用pygame.display.set_mode()创建的surface是特殊的一类,它代表了屏幕对象,无论你在做了什么它都会出现在用户surface上。
  2. 使用image.load()来创建一个包含图像的surface
  3. 使用font.render()来创建一个包含文本的surface
  4. 也可以使用Surface()来创建一个不包含任何内容的surface

   Reprint policy


《Pygame中的convert()》 by 无涯明月 is licensed under a Creative Commons Attribution 4.0 International License
 Previous
Pygame中的Color和显示器display Pygame中的Color和显示器display
Pygame中的Color有下面三种生成Color颜色对象的方式: Color(r, g, b) -> Color Color(r, g, b, a=255) -> Color Color(color_value) -> Color 也就是
2019-09-30
Next 
Pygame初探 Pygame初探
前言:为什么上了研究生才开始试着系统学习Pygame?以前总觉得知道上哪去找就好,也就没那么多的追求。在做小游戏的时候,也是遇到不会的就百度,然后用一点时间就简单解决了,感觉良好。但是实际上是,到了如今阶段还是什么都靠百度。可能到 了某个
2019-09-30
  TOC