如何在PyGame中绘制到屏幕外显示

时间:2014-01-29 19:53:03

标签: python optimization graphics pygame system.drawing

我正在使用PyGame进行图形测试,以模拟正在展开的Dragon Curve。我已经制作了一个成功的版本,可以跟踪所有的点,因为它们相互旋转,但显然,经过几次迭代后,这开始显着减慢。为了加快速度,我想简单地将绘制的段存储到图像变量中,并不断将屏幕的一部分保存到变量中并绘制那些移动而不是跟踪很多点。我该怎么做以下任何一种?

  • 绘制一个离屏图像变量,然后在正确的位置绘制到屏幕
  • 将可见显示的一部分保存到图像变量

我尝试阅读一些PyGame文档,但我没有取得任何成功。

谢谢!

1 个答案:

答案 0 :(得分:2)

创建一个额外的曲面对象,并绘制到它是解决方案。然后可以将此表面对象绘制到显示器的表面对象上,如下所示。

可以找到有关PyGame Surface对象的更多信息here

import pygame, sys

SCREEN_SIZE = (600, 400)
BG_COLOR = (0, 0, 0)
LINE_COLOR = (0, 255, 0)
pygame.init()
clock = pygame.time.Clock() # to keep the framerate down

image1 = pygame.Surface((50, 50))
image2 = pygame.Surface((50, 50))
image1.set_colorkey((0, 0, 0)) # The default background color is black
image2.set_colorkey((0, 0, 0)) # and I want drawings with transparency

screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
screen.fill(BG_COLOR)

# Draw to two different images off-screen
pygame.draw.line(image1, LINE_COLOR, (0, 0), (49, 49))
pygame.draw.line(image2, LINE_COLOR, (49, 0), (0, 49))

# Optimize the images after they're drawn
image1.convert()
image2.convert()

# Get the area in the middle of the visible screen where our images would fit
draw_area = image1.get_rect().move(SCREEN_SIZE[0] / 2 - 25,
                                   SCREEN_SIZE[1] / 2 - 25)

# Draw our two off-screen images to the visible screen
screen.blit(image1, draw_area)
screen.blit(image2, draw_area)

# Display changes to the visible screen
pygame.display.flip()

# Keep the window from closing as soon as it's finished drawing
# Close the window gracefully upon hitting the close button
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit(0)
    clock.tick(30)