如何解决pygame.draw.rect 和 screen_surface.blit() 有什么区别?
我试图让一个红色矩形向右移动,通过使用 pygame.move.rect 或 .blit,我能够完成同样的事情。我可以显示红色矩形并通过按向右箭头将其向右移动。但是,我应该知道这两个功能之间有什么区别吗?为什么有两个函数基本上做同样的事情。
带有 pygame.move.rect 的代码
import pygame
import sys
pygame.init()
#obtain the surface and rect for screen
screen_surface = pygame.display.set_mode((1200,800))
pygame.display.set_caption("Hi")
#Obtain Surface and rect for the rectangle
red_rectangle = pygame.Surface((600,400))
red_rectangle_rect = red_rectangle.get_rect()
#make the rectangle surface red
red_rectangle.fill((255,0))
move_right = False
while True:
#event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
move_right = True
print(event.type)
print(event.key)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
move_right = False
#rectangle move to right when right arrow is pressed
if move_right:
red_rectangle_rect.x += 10
print(red_rectangle_rect.x)
screen_surface.fill((255,255,255))
# the difference between this function and the .blit
pygame.draw.rect(screen_surface,(255,0),red_rectangle_rect)
pygame.display.flip()
.blit 代码
import pygame
import sys
pygame.init()
#obtain the surface and rect for screen
screen_surface = pygame.display.set_mode((1200,0))
move_right = False
while True:
#event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
move_right = True
print(event.type)
print(event.key)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
move_right = False
#rectangle move to right when right arrow is pressed
if move_right: then
red_rectangle_rect.x += 10
print(red_rectangle_rect.x)
screen_surface.fill((255,255))
#Difference between this and the draw function
screen_surface.blit(red_rectangle,red_rectangle_rect)
pygame.display.flip()
解决方法
blit(image,(left,top)) - 在给定位置将图像绘制到屏幕上。该函数接受 Surface 或字符串作为其图像参数。如果 image 是 str ,那么将从 images/ 目录加载命名的图像。
draw.rect(rect,(r,g,b)) - 绘制矩形的轮廓。取一个矩形。
,为什么有 2 个函数基本上做同样的事情。
不,它们不一样。 pygame.draw.rect
绘制统一彩色矩形时,pygame.Surface.blit
是 pygame.Surface
的一种方法,用于绘制位图图像。
rect(surface,color,rect) -> Rect
在给定的表面上绘制一个矩形。
blit(source,dest,area=None,special_flags=0) -> Rect
在这个 Surface 上绘制一个源 Surface
在您的情况下,看起来他们正在做同样的事情,因为您的 Surface 对象均匀地填充了一种颜色。
当您使用 pygame.image.load
加载位图图像时,行为完全改变。您不能使用 pygame.draw.rect
绘制图像,但可以使用 blit
。
何时使用 pygame.draw.rect
,请参阅:
何时使用 blit
,请参阅:
What is a good way to draw images using pygame?
,所以只是为了澄清,
对图像使用 blit,对具有 1 种颜色的矩形使用 rect。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。