pygame 中的surface.blit() 函数是什么?它有什么作用?它是如何工作的?

Lav*_*ani 16 python pygame canvas blit

我是 Python 初学者,对函数不是很清楚surface.blit()。它有什么作用?它是如何工作的?

关于如何创建它,我遇到了以下几点。

  • 创建所需大小的画布
  • 创建一个包含要显示的对象的较小尺寸的表面。
  • 定义表面的 Rect 值。
  • Blit(重叠)画布上矩形位置的表面

句法: canvas.blit(surface, surfacerect)

为什么只使用 rect?可以是其他形状吗?

DCA*_*CA- 21

尽管尽可能简单地将其放在实际中可能会有所帮助 - > blitting 正在绘制

完成您提到的每个步骤:

  • 创建所需大小的画布

这是我们的窗口,由screen = pygame.display.set_mode((width,height)). screen画布名称在哪里。最终,一切都需要绘制到这个画布上,这样我们才能看到它。

  • 创建一个包含要显示的对象的较小尺寸的表面

这是一个我们将用图像等对象填充的表面。它不需要小于窗口大小,可以自由移动。

  • 定义表面的 Rect 值

当您使用诸如background = pygame.Surface((width,height))指定其大小之类的东西创建曲面时。表面上的图像或绘制的项目可以是任何形状或大小,但它们必须全部包含在此宽度和高度设置的边界内。

  • Blit(重叠)画布上矩形位置的表面

现在最重要的一点。我们需要获取这个表面(背景)并将其绘制到窗口上。为此,我们将调用screen.blit(background,(x,y))where (x,y) 是窗口内我们希望表面左上角所在的位置。该函数表示取背景表面并将其绘制到屏幕上并将其定位在 (x,y) 处。

一个简单的例子:

import pygame

pygame.init()

#### Create a canvas on which to display everything ####
window = (400,400)
screen = pygame.display.set_mode(window)
#### Create a canvas on which to display everything ####

#### Create a surface with the same size as the window ####
background = pygame.Surface(window)
#### Create a surface with the same size as the window ####

#### Populate the surface with objects to be displayed ####
pygame.draw.rect(background,(0,255,255),(20,20,40,40))
pygame.draw.rect(background,(255,0,255),(120,120,50,50))
#### Populate the surface with objects to be displayed ####

#### Blit the surface onto the canvas ####
screen.blit(background,(0,0))
#### Blit the surface onto the canvas ####

#### Update the the display and wait ####
pygame.display.flip()
done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
#### Update the the display and wait ####

pygame.quit()
Run Code Online (Sandbox Code Playgroud)