2017-04-26 271 views
0

我一直在試圖使用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行代碼。 –

回答

2

每該文檔(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) 
1

這裏有一個完整的例子。不要修改原始圖像,並在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()