Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

python - How to render/blit text in pygame for good performance

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))

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

At initialization:

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

Once per frame:

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

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)
# [...]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...