在pygame中调整图像大小的正确方法是什么



我在pygame中有一个图像,我的代码会检测这个图像是否被点击。它运行得很好,我决定调整图像的大小,但当我这样做时,图像随机消失了。这是图像消失前的代码:

import pygame
pygame.init()
width = 500
height = 500
screen = pygame.display.set_mode((width, height))
white = (255, 255, 255)
screen.fill(white)
pygame.display.set_caption('Aim Trainer')
target = pygame.image.load("aim target.png").convert_alpha()
x = 20  # x coordinate of image
y = 30  # y coordinate of image
screen.blit(target, (x, y))  # paint to screen
pygame.display.flip()  # paint screen one time
targetSize = pygame.transform.scale(target, (5, 3))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
# Set the x, y positions of the mouse click
x, y = event.pos
if target.get_rect().collidepoint(x, y):
print('clicked on image')
# loop over, quite pygame
pygame.quit()

这是我的代码后:

import pygame
pygame.init()
width = 500
height = 500
screen = pygame.display.set_mode((width, height))
white = (255, 255, 255)
screen.fill(white)
pygame.display.set_caption('Aim Trainer')
target = pygame.image.load("aim target.png").convert_alpha()
x = 20  # x coordinate of image
y = 30  # y coordinate of image
pygame.display.flip()  # paint screen one time
targetSize = pygame.transform.scale(target, (5, 3))
screen.blit(targetSize, (x, y))  # paint to screen
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
# Set the x, y positions of the mouse click
x, y = event.pos
if target.get_rect().collidepoint(x, y):
print('clicked on image')
# loop over, quite pygame
pygame.quit()

正如你所看到的,唯一改变的是我将screen.blit(target, (x, y))重命名为screen.blit(targetSize, (x, y)),并将这行代码进一步下移几行,以避免出现"TargetSize未定义"错误。但由于某种原因,这种变化使图像消失了。当我点击图像时,程序仍然会检测到它,只是图像不可见。

  1. 您必须从缩放的iamage 中获取矩形

  2. pygame.Surface.get_rect()返回一个矩形,其大小与Surface对象的大小相同,该矩形始终从(0,0(开始,因为Surfaceobject没有位置。曲面是屏幕上某个位置的blit。矩形的位置可以通过关键字参数指定。例如,可以使用关键字参数topleft指定矩形的左上角。这些关键字参数在返回pygame.Rect之前应用于其属性(有关关键字参数的完整列表,请参阅pygame.Rect(。

  3. 绘制图像后更新显示

targetSize = pygame.transform.scale(target, (5, 3))
target_rect = targetSize.get_rect(topleft = (x, y))
screen.blit(targetSize, (x, y))
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
if target_rect.collidepoint(event.pos):
print('clicked on image')

相关内容

  • 没有找到相关文章

最新更新