What’s the difference between Texture and Surface? It seems that most of the time I have to create Surface and then creating a Texture with SDL_CreateTextureFromSurface
When I copy the Texture to the Rendere with SDL_RenderCopy I can use both srcrect and dstrect. If I understood correctly srcrect is used for “sprite” so that I can crop the image, but dstrect is used both for positioning and streching. How can I set position by avoiding streching ? It’s kind of hard avoiding the streching when rendering text (I don’t know how to calculate the width)
Surface is stored in RAM and drawing is performed on the CPU. Texture is stored in Video RAM (GPU RAM) and drawing is performed by the GPU. If you need best performance, use textures only, because GPU can render things million times faster than the CPU.
No, you don’t need to use surfaces at all. You can create texture using the SDL_CreateTexture function and render anything on it. If you need to load image e.g. from file and store it in the form of texture, you can do it via IMG_LoadTexture function — SDL will do everything for you internally.
Correct.
Write some more what stretching you are talking about. Do you want to render the texture with original size or using stretching but keeping correct aspect ratio?
If you would like to scale an image while maintaining the same aspect ratio, then multiply the rectangle w and h by any scalar value:
// just don't let the scalar be a negative number
// SDL_RenderCopy doesn't like it's rectangles to be size-negative.
void scaleRect(SDL_Rect &pos, float scalar)
{
pos.w = ((float) pos.w) * scalar;
pos.h = ((float) pos.h) * scalar;
}
Here’s some other “helpful hints”
void setRectPosition(SDL_Rect &pos, int x, int y)
{
pos.x = x;
pos.y = y;
}
void moveRect(SDL_Rect &pos, int x, int y)
{
pos.x += x;
pos.y += y;
}
// again: error checking to avoid negative width and height could be used
void resizeRect(SDL_Rect &pos, int w, int h)
{
pos.w = w;
pos.h = h;
}
You can also query the texture to get it’s original size, which is the size of the surface that it was created from: → SDL2/SDL_QueryTexture - SDL Wiki
Or you can use SDL_SetRenderTarget(renderer, texture); and then use SDL_GetRendererOutputSize(renderer, &width, &height); → SDL2/SDL_GetRendererOutputSize - SDL Wiki
(Please note that in SDL3 this function has changed names to → SDL3/SDL_GetCurrentRenderOutputSize - SDL Wiki
(Even though I’m kind of joking, I have used this version in a pinch for some reason or other that I don’t remember.)