Implementing zooming functionality for images in SDL2 involves manipulating the source and destination rectangles when blitting.
Here's how you can modify our Image
class to support zooming:
#include <SDL.h>
#include <algorithm>
#include <iostream>
#include <string>
class Image {
public:
Image(std::string File,
SDL_PixelFormat* PreferredFormat =
nullptr)
: ImageSurface{SDL_LoadBMP(File.c_str())},
ZoomLevel{1.0f} {
// Constructor code remains the same
}
void Render(SDL_Surface* DestinationSurface,
int x, int y) {
int zoomedWidth = static_cast<int>(
ImageSurface->w * ZoomLevel);
int zoomedHeight = static_cast<int>(
ImageSurface->h * ZoomLevel);
SDL_Rect srcRect{
0, 0, ImageSurface->w, ImageSurface->h};
SDL_Rect destRect{
x, y, zoomedWidth, zoomedHeight};
SDL_BlitScaled(ImageSurface, &srcRect,
DestinationSurface,
&destRect);
}
void SetZoom(float zoom) {
// Prevent negative or zero zoom
ZoomLevel = std::max(0.1f, zoom);
}
float GetZoom() const { return ZoomLevel; }
// Rest of the class remains unchanged
private:
SDL_Surface* ImageSurface;
float ZoomLevel;
};
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window =
SDL_CreateWindow("Zoomable Image",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
800, 600, 0);
SDL_Surface* screenSurface =
SDL_GetWindowSurface(window);
Image img{
"example.bmp", screenSurface->format};
bool quit = false;
SDL_Event e;
while (!quit) {
while (SDL_PollEvent(&e) != 0) {
if (e.type == SDL_QUIT) {
quit = true;
} else if (e.type == SDL_KEYDOWN) {
switch (e.key.keysym.sym) {
case SDLK_PLUS:
case SDLK_KP_PLUS:
// Zoom in
img.SetZoom(img.GetZoom() * 1.1f);
break;
case SDLK_MINUS:
case SDLK_KP_MINUS:
// Zoom out
img.SetZoom(img.GetZoom() / 1.1f);
break;
}
}
}
SDL_FillRect(screenSurface, nullptr,
SDL_MapRGB(
screenSurface->format,
255, 255, 255
)
);
// Center of 800x600 window
img.Render(screenSurface, 400, 300);
SDL_UpdateWindowSurface(window);
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
In this implementation, we've added a ZoomLevel
member to our Image
class. The SetZoom()
method allows us to change the zoom level, while GetZoom()
lets us retrieve the current zoom level.
The Render()
method now calculates the zoomed dimensions and uses SDL_BlitScaled()
to draw the image at the correct size. In the main loop, we handle keyboard events to zoom in and out using the plus and minus keys.
For a more advanced zoom implementation, you might want to:
Remember, frequent scaling operations can be computationally expensive. For complex scenes or low-end devices, consider using texture rendering with SDL's GPU acceleration features for better performance.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to load, display, and optimize image rendering in your applications