Search code examples
pythonpython-3.xpygamezooming

pygame.transform.scale does not work on the "game" surface


I am writing a program and I want to zoom in and out where the cursor is positioned.

I have tried (maybe foolishly) to pygame.transform.scale2x the window (which is basically my whole window with the game so:

window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
pygame.transform.scale2x(window)

)

Is there any other solution? What am I doing wrong with the pygame.transform.scale2x (I reckon pygame.transform is just for images so how can I use it on a surface?)? It would be great if the solution did not include changing all of the coordinates of pygame.draw methods as I have a lot of them in my program. Thanks in advance!


Solution

  • I want to zoom in and out where the cursor is positioned.

    Define a zoom factor and calculate the size of the of the zoom area. e.g. If the zoom factor is 2, the area that needs to be zoomed on the window is half the width and height of the window:

    zoom = 2
    
    wnd_w, wnd_h = window.get_size()
    zoom_size = (round(wnd_w/zoom), round(wnd_h/zoom))
    

    Define the rectangular zoom area. The center point of the area is the position where to zoom to. (e.g the cursor position):

    zoom_area = pygame.Rect(0, 0, *zoom_size)
    zoom_area.center = (pos_x, pos_y)
    

    Create a new pygame.Surface with the size of the zoom area and copy the region of the window to the surface, by using ,blit, where the area parameter is set to the zoom region:

    zoom_surf = pygame.Surface(zoom_area.size)
    zoom_surf.blit(screen, (0, 0), zoom_area)
    

    Scale zoom_surf by either pygame.transform.scale() or pygame.transform.smoothscale():

    zoom_surf = pygame.transform.scale(zoom_surf, (wnd_w, wnd_h))
    

    Now zoom_surf has the same size as the window. .blit the surface to the window:

    window.blit(zoom_surf, (0, 0))