Scaling sprites in SDL
How can i scal开发者_开发技巧e sprites in SDL?
SDL doesn't provide scaling functionality directly, but there's an additional library called SDL_gfx which provides rotation and zooming capabilities. There's also another library called Sprig which provides similar features.
You can do scaling if you are getting sprites from a texture with SDL_RenderCopy() but i cannot guarantee you antialiasing.
With function SDL_RenderCopy() you pass 4 params:
- a pointer to a renderer (where you are going to renderize).
- a pointer to a texture (where you are going to get the sprite).
- pointer to source rect(the area and position where you get the sprite on the texture).
- and pointer to dest rect(the area and position on the renderer you are going to draw).
You should only modify your dest rect like for example, if you are going to render an image 300 x 300 and you want it scaled, your dest rect should be like 150 x 150 or 72 x 72 or whatever value you wanted to scale.
You haven't provided any code, so I'm going to assume you are using textures and an SDL_Renderer:
When using SDL_RenderCopy() the texture will be stretched to fit the destination SDL_Rect, so if you make the destination SDL_Rect larger or smaller you can perform a simple scaling of the texture.
https://wiki.libsdl.org/SDL_RenderCopy
Solution from Ibrahim CS works.
Let me expand on top of this solution and providing the code. Another thing to note is to calculate new position (x,y) with top-left is origin to render 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);
assume that texture
is SDL_Texture
, and renderer
is SDL_Renderer
, and you render fully from input texture to destination.
If you use SFML instead then you get a very similar set of cross-platform capabilities but the graphics are hardware accelerated and features such as scaling and rotation come for free, both in terms of needing no additional dependencies and in terms of taking no noticeable CPU time to operate.
精彩评论