pygame rotate image

Solutions on MaxInterview for pygame rotate image by the best coders in the world

showing results for - "pygame rotate image"
Niclas
22 Jan 2019
1import pygame
2import pygame.font
3
4pygame.init()
5size = (400,400)
6screen = pygame.display.set_mode(size)
7clock = pygame.time.Clock()
8
9def blitRotate(surf, image, pos, originPos, angle):
10
11    # calcaulate the axis aligned bounding box of the rotated image
12    w, h       = image.get_size()
13    box        = [pygame.math.Vector2(p) for p in [(0, 0), (w, 0), (w, -h), (0, -h)]]
14    box_rotate = [p.rotate(angle) for p in box]
15    min_box    = (min(box_rotate, key=lambda p: p[0])[0], min(box_rotate, key=lambda p: p[1])[1])
16    max_box    = (max(box_rotate, key=lambda p: p[0])[0], max(box_rotate, key=lambda p: p[1])[1])
17
18    # calculate the translation of the pivot 
19    pivot        = pygame.math.Vector2(originPos[0], -originPos[1])
20    pivot_rotate = pivot.rotate(angle)
21    pivot_move   = pivot_rotate - pivot
22
23    # calculate the upper left origin of the rotated image
24    origin = (pos[0] - originPos[0] + min_box[0] - pivot_move[0], pos[1] - originPos[1] - max_box[1] + pivot_move[1])
25
26    # get a rotated image
27    rotated_image = pygame.transform.rotate(image, angle)
28
29    # rotate and blit the image
30    surf.blit(rotated_image, origin)
31
32    # draw rectangle around the image
33    pygame.draw.rect (surf, (255, 0, 0), (*origin, *rotated_image.get_size()),2)
34
35font = pygame.font.SysFont('Times New Roman', 50)
36text = font.render('image', False, (255, 255, 0))
37image = pygame.Surface((text.get_width()+1, text.get_height()+1))
38pygame.draw.rect(image, (0, 0, 255), (1, 1, *text.get_size()))
39image.blit(text, (1, 1))
40w, h = image.get_size()
41
42angle = 0
43done = False
44while not done:
45    clock.tick(60)
46    for event in pygame.event.get():
47        if event.type == pygame.QUIT:
48            done = True
49        elif event.type == pygame.KEYDOWN:
50            if event.key==pygame.K_ESCAPE:
51                done = True
52
53    pos = (screen.get_width()//2, screen.get_height()//2)
54    pos = (200, 200)
55
56    screen.fill(0)
57    blitRotate(screen, image, pos, (w//2, h//2), angle)
58    angle += 1
59
60    pygame.draw.line(screen, (0, 255, 0), (pos[0]-20, pos[1]), (pos[0]+20, pos[1]), 3)
61    pygame.draw.line(screen, (0, 255, 0), (pos[0], pos[1]-20), (pos[0], pos[1]+20), 3)
62    pygame.draw.circle(screen, (0, 255, 0), pos, 7, 0)
63
64    pygame.display.flip()
65
66pygame.quit()
67