pyGame 图像缩放未按预期工作

pyGame image scale does not work as expected

我是 Python 和 pyGame 的新手,我在缩放图像时遇到问题。 我想在 pygame 中放大图像。 pygame 文档声称

pygame.transform.scale()

应该缩放到新的分辨率。 但在我下面的示例中它不起作用 - 它裁剪图像而不是调整图像大小!? 我究竟做错了什么?

#!/usr/bin/env python3
# coding: utf-8

import pygame
from pygame.locals import *

# Define some colors
BLACK = (0, 0, 0)

pygame.init()

# Set the width and height of the screen [width, height]
screen = pygame.display.set_mode((1920, 1080))

pic = pygame.image.load('test.jpg').convert()
pic_position_and_size = pic.get_rect()

# Loop until the user clicks the close button.
done = False

# Clear event queue
pygame.event.clear()

# -------- Main Program Loop -----------
while not done:
    for event in pygame.event.get():
        if event.type == QUIT:
            done = True
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                done = True

    # background in black
    screen.fill(BLACK)

    # Copy image to screen:
    screen.blit(pic, pic_position_and_size)

    # Update the screen with what we've drawn.
    pygame.display.flip()
    pygame.display.update()

    pygame.time.delay(10)    # stop the program for 1/100 second

    # decreases size by 1 pixel in x and y axis
    pic_position_and_size = pic_position_and_size.inflate(-1, -1)

    # scales the image
    pic = pygame.transform.scale(pic, pic_position_and_size.size)

# Close the window and quit.
pygame.quit()

pygame.transform.scale() 不适合你的情况。如果将 Surface 缩小这么小,算法只会裁剪最后一列和最后一行像素。如果你现在用相同的 Surface 一遍又一遍地重复这个过程,你会看到你看到的奇怪行为。

更好的方法是保留原始 Surface 的副本,并使用它来创建缩放图像。另外,用smoothscale代替scale也可能会达到更好的效果;想用就看你了

这是您的代码的 "fixed" 版本:

#!/usr/bin/env python3
# coding: utf-8

import pygame
from pygame.locals import *

# Define some colors
BLACK = (0, 0, 0)

pygame.init()

# Set the width and height of the screen [width, height]
screen = pygame.display.set_mode((1920, 1080))

org_pic = pygame.image.load('test.jpg').convert()
pic_position_and_size = org_pic.get_rect()
pic = pygame.transform.scale(org_pic, pic_position_and_size.size)
# Loop until the user clicks the close button.
done = False

# Clear event queue
pygame.event.clear()

# -------- Main Program Loop -----------
while not done:
    for event in pygame.event.get():
        if event.type == QUIT:
            done = True
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                done = True

    # background in black
    screen.fill(BLACK)

    # Copy image to screen:
    screen.blit(pic, (0,0))

    # Update the screen with what we've drawn.
    pygame.display.flip()
    pygame.display.update()

    pygame.time.delay(10)    # stop the program for 1/100 second

    # decreases size by 1 pixel in x and y axis
    pic_position_and_size = pic_position_and_size.inflate(-1, -1)

    # scales the image
    pic = pygame.transform.smoothscale(org_pic, pic_position_and_size.size)

# Close the window and quit.
pygame.quit()