如何在 pygame 中渲染/blit 文本以获得良好的性能 [英] How to render/blit text in pygame for good performance

查看:164
本文介绍了如何在 pygame 中渲染/blit 文本以获得良好的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Pygame 开发一个小游戏(作为爱好).在此之前,我从未在图形界面上工作过,并且遇到了一些性能问题.即使在选项菜单中,FPS 似乎也被限制在 110 左右,这听起来可能还不错,但考虑到它只是一个带有一些文字的黑屏,FPS 肯定应该更高.这是其中一个文本框的代码:

I am working on a small game (as a hobby) using Pygame. Before this I never worked on graphical interfaces and I am encountering some performance issues. Even in the options menu the FPS seem to be capped at around 110, which maybe doesn't sound that bad, but considering it is just a black screen with some text on it the FPS definitely should be higher. This is the code for one of the textboxes:

font = pygame.font.SysFont("Comic Sans MS", 180)
color = (0,60,20)
screen.blit(font.render("Title", False, color), (480,0))

选项菜单只有大约 15 个文本框,这已经导致 FPS 问题.我渲染或位图文本的方式有问题吗?

The options menu is nothing but around 15 of those textboxes and this already causes FPS issues. Is something wrong with how I am rendering or blitting the text?

推荐答案

不要在每一帧中创建 pygame.font.Font 对象,也不要在每一帧中渲染文本.在程序开始时或在类的构造函数 (__init__) 中创建文本 Surface 一次.只需 blit 文本 Surface 在每一帧中:

Do not create the pygame.font.Font object in every frame and do not render the text in every frame. Create the text Surface once at the begin of the program or in the constructor (__init__) of a class. Just blit the text Surface in every frame:

初始化时:

font = pygame.font.SysFont("Comic Sans MS", 180)
color = (0,60,20)
text_surface = font.render("Title", False, color)

每帧一次:

screen.blit(text_surface, (480,0))

如果文本是动态的,它甚至无法预渲染.然而,最耗时的是创建pygame.font 对象.至少,您应该避免在每一帧中都创建字体.
在典型的应用程序中,您不需要字体和字体大小的所有排列.您只需要几个不同的 font 对象.在应用程序开始时创建一些字体并在呈现文本时使用它们.例如:

If the text is dynamic, it cannot even be pre-rendered. However, the most time-consuming is to create the pygame.font object. At the very least, you should avoid creating the font in every frame.
In a typical application you don't need all permutations of fonts and font sizes. You just need a couple of different font objects. Create a number of fonts at the beginning of the application and use them when rendering the text. For Instance:

fontComic40  = pygame.font.SysFont("Comic Sans MS", 40)
fontComic180 = pygame.font.SysFont("Comic Sans MS", 180)
# [...]

这篇关于如何在 pygame 中渲染/blit 文本以获得良好的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆