在Pygame中旋转图像不失真

问题描述:

我一直在试图使用python 3.6在pygame中旋转图像,但是当我这样做时,它要么扭曲图像变成无法识别的图像,要么当它旋转时,它碰到各处在Pygame中旋转图像不失真

只使用pygame.transform.rotate(image, angle)会使扭曲的混乱。 并使用类似的东西: pygame.draw.rect(gameDisplay, self.color, [self.x, self.y, self.width, self.height])使图像碰到各地。

我看了很多关于这个网站和其他人的问题,到目前为止他们都没有完美的工作。 任何对此感兴趣的人都可以看到我的代码到目前为止的链接。 https://pastebin.com/UQJJFNTy 我的图像是64x64。 在此先感谢!

+3

创建[mcve]。我想最多是10行代码。 –

每该文档(http://www.pygame.org/docs/ref/transform.html):

一些变换的被认为是破坏性的。这些意味着每次执行它们都会丢失像素数据。常见的例子是调整大小和旋转。 由于这个原因,重新转换原始表面要比多次转换图像要好。

每次调用transform.rotate你需要做的是在原始图像上时,在之前旋转一周。例如,如果我想图像旋转10度,每一帧:

image = pygame.image.load("myimage.png").convert() 
image_clean = image.copy() 
rot = 0 

然后在你的游戏循环(或对象的update):

rot += 10 
image = pygame.transform.rotate(image_clean, rot) 

这里有一个完整的例子。不要修改原始图像,并在while循环中使用pygame.transform.rotaterotozoom来获取新的旋转曲面并将其分配给其他名称。使用矩形来保持中心。

import sys 
import pygame as pg 


pg.init() 
screen = pg.display.set_mode((640, 480)) 

BG_COLOR = pg.Color('darkslategray') 
# Here I just create an image with per-pixel alpha and draw 
# some shapes on it so that we can better see the rotation effects. 
ORIG_IMAGE = pg.Surface((240, 180), pg.SRCALPHA) 
pg.draw.rect(ORIG_IMAGE, pg.Color('aquamarine3'), (80, 0, 80, 180)) 
pg.draw.rect(ORIG_IMAGE, pg.Color('gray16'), (60, 0, 120, 40)) 
pg.draw.circle(ORIG_IMAGE, pg.Color('gray16'), (120, 180), 50) 


def main(): 
    clock = pg.time.Clock() 
    # The rect where we'll blit the image. 
    rect = ORIG_IMAGE.get_rect(center=(300, 220)) 
    angle = 0 

    done = False 
    while not done: 
     for event in pg.event.get(): 
      if event.type == pg.QUIT: 
       done = True 

     # Increment the angle, then rotate the image. 
     angle += 2 
     # image = pg.transform.rotate(ORIG_IMAGE, angle) # rotate often looks ugly. 
     image = pg.transform.rotozoom(ORIG_IMAGE, angle, 1) # rotozoom is smoother. 
     # The center of the new rect is the center of the old rect. 
     rect = image.get_rect(center=rect.center) 
     screen.fill(BG_COLOR) 
     screen.blit(image, rect) 

     pg.display.flip() 
     clock.tick(30) 


if __name__ == '__main__': 
    main() 
    pg.quit() 
    sys.exit()