[英]Rotating An Image In Pygame Without Distortion
我一直在嘗試使用python 3.6在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。 提前致謝!
根據文檔( 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.rotate
或rotozoom
獲取新的旋轉表面並將其分配給另一個名稱。 使用矩形保持中心。
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.