2016-10-27 118 views
0

这里是我的代码(Python的3.5):如何旋转图像而不丢失像素数据? (pygame的)

import sys 
import pygame 
pygame.init() 

screen_width = 640 
screen_height = 480 
screen = pygame.display.set_mode((screen_width, screen_height)) 
running = True 

class Actor: 

    def __init__(self, x, y, w, h): 
     self.x = x 
     self.y = y 
     self.w = w 
     self.h = h 
     self.surface = pygame.image.load("GFX/player.bmp") 

    def draw(self): 
     screen.blit(self.surface, (self.x, self.y)) 

class Player(Actor): 

    def __init__(self): 
     Actor.__init__(self, 0, 0, 32, 32) 
     self.directions = [False, False, False, False] 
     self.speed = 0.1 

    def update(self): 
     if self.directions[0]: 
      self.y -= self.speed 
     if self.directions[1]: 
      self.y += self.speed 
     if self.directions[2]: 
      self.x -= self.speed 
     if self.directions[3]: 
      self.x += self.speed 

player = Player() 

def rot_center(image, angle): 
    orig_rect = image.get_rect() 
    rot_image = pygame.transform.rotate(image, angle) 
    rot_rect = orig_rect.copy() 
    rot_rect.center = rot_image.get_rect().center 
    rot_image = rot_image.subsurface(rot_rect).copy() 
    return rot_image 

def redraw(): 
    screen.fill((75, 0, 0)) 
    player.draw() 
    player.update() 
    pygame.display.flip() 

while (running): 
    for e in pygame.event.get(): 
     if e.type == pygame.QUIT: 
      sys.exit() 
     elif e.type == pygame.KEYDOWN: 
      if e.key == pygame.K_ESCAPE: 
       sys.exit() 
      if e.key == pygame.K_w: 
       player.directions[0] = True 
      if e.key == pygame.K_s: 
       player.directions[1] = True 
      if e.key == pygame.K_a: 
       player.directions[2] = True 
      if e.key == pygame.K_d: 
       player.directions[3] = True 
     elif e.type == pygame.KEYUP: 
      if e.key == pygame.K_w: 
       player.directions[0] = False 
      if e.key == pygame.K_s: 
       player.directions[1] = False 
      if e.key == pygame.K_a: 
       player.directions[2] = False 
      if e.key == pygame.K_d: 
       player.directions[3] = False 
     elif e.type == pygame.MOUSEMOTION: 
      player.surface = rot_center(player.surface, pygame.mouse.get_pos()[0]/64) 

    redraw() 

非常简单的pygame的代码。我有一个用mspaint创建的简单图像的播放器,我用this function来旋转图像而不会导致内存不足的问题。我用鼠标旋转图像(考虑到某个玩家“瞄准”某个地方)。这里的原始图像:

enter image description here

在这里,移动鼠标一点后是极其丑陋的结果:

enter image description here

我知道我会使用OpenGL(Pyglet,对于具有更高的精度例子),但在这种情况下pygame的旋转函数将完全无用。我错过了什么?我究竟做错了什么?

+0

始终使用oryginal图像来生成旋转的版本。或者在图形编辑器中创建旋转图像,并使用它们而不是'pygame.transform.rotate' – furas

回答

1

请记住,Python中的曲面只是像素的网格,而不是数学上完美的矢量图形。旋转图像会导致质量轻微损坏。如果你继续这样做,最终会让你的照片中看到的图像变得无法识别。保持对原始图像的引用并永不覆盖它。当您调用旋转时,请确保您正在旋转原始照片,并且相对于原始照片具有累积角度,而不是先前和递增旋转的版本。