在Python中更新表面的一部分或透明表面
我有一个用Python写的应用程序,基本上就是一个电子画板,你可以用WASD键和方向键移动像素,并且它会留下轨迹。不过,我想加一个计数器,显示屏幕上有多少个像素。请问我该怎么让这个计数器更新,而不影响整个画面和已经画好的像素呢?
另外,我能不能做一个完全透明的表面,除了文字之外什么都看不见,这样就能看到下面的画布了?
2 个回答
0
你需要的是pygame.font模块
#define a font surface
spamSurface = pygame.font.SysFont('Arial', 20)
#then, in your infinite cycle...
eggsPixels = spamSurface.render(str(pixelsOnScreen), True, (255, 255, 255))
hamDisplay.blit(eggsPixels, (10, 10))
这里的spamSurface
是一个新的字体表面,eggsPixels
是spamSurface
要显示的内容,而hamDisplay
就是你主要的显示区域。
1
要解决这个问题,你需要为你的Etch-a-Sketch像素准备一个单独的画布,这样在刷新屏幕的时候就不会把之前的内容覆盖掉。不过,Rigo的方案会导致字体在自己上面重复渲染,这样如果像素变化超过两个,就会变得很乱。
下面是一些示例渲染代码:
# Fill background
screen.fill((0xcc, 0xcc, 0xcc))
# Blit Etch-a-Sketch surface (with the drawing)
# etch_surf should be the same size as the screen
screen.blit(etch_surf, (0, 0))
# Render the pixel count
arial = pygame.font.SysFont('Arial', 20)
counter_surf = arial.render(str(pixel_count), True, (0, 0, 0))
screen.blit(counter_surf, (16, 16))
# Refresh entire screen
pygame.display.update()
确实,更新整个屏幕效率不高。对此,你有两个选择:要么在绘图变化时才刷新屏幕,要么跟踪绘图变化的位置,只刷新那些地方(可以参考更新文档)。如果你选择第二个选项,你需要刷新文本和它之前的位置;我建议使用一个精灵来管理这个过程。