What does the parameter DestSurface in Pygame.transform.scale mean and how do I use it?

Question:

The documentation for the pygame.transform.scale method is as follows.

scale(Surface, (width, height), DestSurface = None) -> Surface`

Resizes the Surface to a new resolution. This is a fast scale operation that does not sample the results.

An optional destination surface can be used, rather than have it create a new one. This is quicker if you want to repeatedly scale something. However the destination must be the same size as the (width, height) passed in. Also the destination surface must be the same format."

I am trying to figure out what Destination surface is. I am assuming that it has something do with the fact that a new surface object is created whenever I rescale a surface and how I can avoid it using DestSurface ?

Asked By: JJoa7

||

Answers:

pygame.transform.scale() does not scale the input Surface itself. It creates a new surface and does a scaled “blit” to the new surface. The new surface is returned by the return value:

pygame.transform.scale() does:

  1. Creates a new surface (newSurface) with size (width, height).
  2. Scale and copy Surface to newSurface.
  3. Return newSurface.

The destination surface is a pygame.Surface where the scaled surface is copied to. That is quicker, because the memory for the Surface has not to be allocated.

It DestSurface is set, then pygame.transform.scale() does:

  1. Scale and copy Surface to the DestSurface.
  2. Return DestSurface.

For that reason, the size of DestSurface has to be (width, height), the format of DestSurface has the same as the format of Surface.


A possible use case is if you have to continuously scale something to a fixed size in the main application loop (e.g. if the surface is dynamically generated). In the following surf is assumed to be a surface object:

while True:
    # [...]

    scaledSurf = pygame.transform.scale(surf, (100, 100)) 
    window.blit(scaledSurf, (x, y)

The code can be improved by using the DestSurface parameter:

scaledSurf = pygame.Surface((100, 100))

while True:
    # [...]

    pygame.transform.scale(surf, (100, 100), scaledSurf) 
    window.blit(scaledSurf, (x, y)

That is probably a rare case. In general you should try to scale the surfaces at the initialization, rather than continuously in the application loop and to use the scaled surfaces in the loop.


Do not try to use the parameter compulsively and do not “construct” a use case for the DestSurface parameter. Do it the other way around. Write your application and make it run. Then investigate whether the DestSurface parameter can be an improvement for your specific use case.

Answered By: Rabbid76
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.