Skip to content

Instantly share code, notes, and snippets.

@NSG650
Created September 11, 2023 07:34
Show Gist options
  • Save NSG650/a1274b3b49469557587585e0d7e9c4b0 to your computer and use it in GitHub Desktop.
Save NSG650/a1274b3b49469557587585e0d7e9c4b0 to your computer and use it in GitHub Desktop.
Fit To Screen Implementation in SDL2 and C
#include <stdio.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <stdint.h>
#include <stddef.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include "stb_image_resize.h"
void stb_fix_colors(uint32_t *img, int width, int height) {
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
uint8_t *rgba = (uint8_t *)&img[i + j * width];
uint8_t new[4];
new[3] = 0xff;
new[2] = rgba[0];
new[1] = rgba[1];
new[0] = rgba[2];
uint32_t new_color = *(uint32_t*)&new;
img[i + j * width] = new_color;
}
}
}
double fit_to_screen_scale_factor(double width, double height, double target_width, double target_height) {
double factor_x = target_width / width;
double factor_y = target_height / height;
double ret = factor_x > factor_y ? factor_y : factor_x;
return ret;
}
int main(void) {
SDL_Init(SDL_INIT_VIDEO);
int width, height, channels;
double new_x, new_y;
uint32_t *img = (uint32_t *)stbi_load("2560x1440.png", &width, &height, &channels, 4);
double factor = fit_to_screen_scale_factor(width, height, 1280, 800);
new_x = width * factor;
new_y = height * factor;
uint32_t *new_img = malloc((int)new_x * (int)new_y * 4);
if (!img || !new_img) return -1;
stb_fix_colors(img, width, height);
stbir_resize_uint8((void*)img, width, height, 0, (void*)new_img, (int)new_x, (int)new_y, 0, 4);
SDL_Window * window = SDL_CreateWindow("Fixing Fit",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
1280, 800,
0);
while (1) {
SDL_Event event = {0};
SDL_Surface *window_surface = SDL_GetWindowSurface(window);
uint32_t *fb = window_surface->pixels;
uint32_t res_x, res_y;
res_x = window_surface->w;
res_y = window_surface->h;
{
uint32_t offset_x = (res_x / 2) - ((int)new_x / 2);
uint32_t offset_y = (res_y / 2) - ((int)new_y / 2);
memset(fb, 0, res_x * res_y * 4);
for (int j = 0; j < new_y; j++) {
memcpy(&fb[offset_x + (j + offset_y) * res_x], &new_img[j * (int)new_x], (int)new_x * 4);
}
}
SDL_UpdateWindowSurface(window);
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) exit(0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment