Scaling sprites in SDL

How can I scale sprites in SDL?

+6
scale sdl image-scaling sprite
source share
5 answers

SDL does not provide scaling functions directly, but there is an additional library called SDL_gfx that provides rotation and scaling capabilities. There's also another library called Sprig , which provides similar features.

+8
source share

You can do the scaling if you get sprites from the texture using SDL_RenderCopy (), but I cannot guarantee anti-aliasing.

With the SDL_RenderCopy () function, you pass 4 parameters:

  • pointer to the renderer (where you are going to display).
  • pointer to the texture (where you are going to get the sprite).
  • pointer to the source rectangle (the area and position where you get the sprite on the texture).
  • and a pointer to dest rect (the area and position on the renderer that you are going to draw).

You only need to change your dest rect, for example, if you are going to display a 300 x 300 image and you want to scale it, your dest rect should be like 150 x 150 or 72 x 72, or any other value that you wanted to scale.

+1
source share

You have not provided any code, so I assume that you are using textures and SDL_Renderer:

When using SDL_RenderCopy (), the texture will be stretched according to the target SDL_Rect, so if you make the target SDL_Rect larger or smaller, you can simply scale the texture.

https://wiki.libsdl.org/SDL_RenderCopy

-one
source share

The solution from Ibrahim CS works.

Let me expand this solution and provide code. Another thing to note is to compute the new position (x, y) with the top left to produce a scaled texture.

I do it like this

// calculate new x and y int new_x = (x + texture->w/2) - (texture->w/2 * new_scale); int new_y = (y + texture->h/2) - (texture->h/2 * new_scale); // form new destination rect SDL_Rect dest_rect = { new_x, new_y, texture->w * scale, texture->h * scale }; // render SDL_RenderCopy(renderer, texture, NULL, &dest_rect); 

Suppose texture is SDL_Texture and renderer is SDL_Renderer and you are completely SDL_Renderer from the input texture to the destination.

-one
source share

If you use SFML , instead you get a very similar set of cross-platform capabilities, but graphics are hardware accelerated and features such as scaling and rotation are provided for free, both in terms of the absence of additional dependencies and in terms of the lack of noticeable processor time for work.

-3
source share

All Articles