2016-03-01 2 views
2

Я новичок в Python и pyGame, и у меня проблема с масштабированием изображения. Я хочу увеличить изображение в 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() 

ответ

1

pygame.transform.scale() не подходит для вашего случая. Если вы уменьшите Surface на такую ​​небольшую сумму, алгоритм просто посещает последний столбец и ряд пикселей. Если вы повторите этот процесс снова и снова с тем же Surface, вы получите странное поведение, которое вы видите.

Лучшим подходом было бы сохранить копию вашего оригинала Surface и использовать его для создания масштабированного изображения. Кроме того, использование smoothscale вместо 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)) 

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() 
+0

Большое спасибо за быстрый ответ! Решила мою проблему! Тем не менее, я задаюсь вопросом, почему это не упоминается в документации pygame ... брал у меня часы, чтобы поиграть, и я пробовал все ... – Franky1

Смежные вопросы