libscgui/Window.cpp
2020-10-23 12:43:47 +02:00

65 lines
2.0 KiB
C++

//
// Window.cpp
// gui
//
// Created by Bob Polis at 2020-10-14
// Copyright (c) 2020 SwiftCoder. All rights reserved.
//
#include <SDL2/SDL_image.h>
#include <cmath>
#include "Window.hpp"
Window::Window(const char* title) : _path {title} {
SDL_Window* win = SDL_CreateWindow(title,
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
900, 540,
SDL_WINDOW_RESIZABLE);
_w.reset(win);
_r.reset(SDL_CreateRenderer(win, -1, 0));
}
void Window::set_size(int w, int h) {
SDL_SetWindowSize(_w.get(), w, h);
}
void Window::update() const {
SDL_RenderClear(_r.get());
SDL_RenderCopy(_r.get(), _t.get(), nullptr, nullptr);
SDL_RenderPresent(_r.get());
}
void Window::load_image() {
// load image from file into surface
SDL_Surface* loaded = IMG_Load(_path.c_str());
if (!loaded) throw std::runtime_error(IMG_GetError());
std::unique_ptr<SDL_Surface, void(*)(SDL_Surface*)> loaded_ {loaded, SDL_FreeSurface};
// create texture from surface
_t.reset(SDL_CreateTextureFromSurface(_r.get(), loaded));
// query texture for properties, like image size
Uint32 format;
int access;
int w, h;
int result = SDL_QueryTexture(_t.get(), &format, &access, &w, &h);
if (result != 0) throw std::runtime_error(SDL_GetError());
// get screen size, to scale down if image is too big
SDL_DisplayMode dm;
SDL_GetCurrentDisplayMode(0, &dm);
if (dm.w < w || dm.h < h) {
double screen_ratio {static_cast<double>(dm.w) / dm.h};
double image_ratio {static_cast<double>(w) / h};
const int safety {100}; // room for window and desktop adornments
if (screen_ratio > image_ratio) { // screen relatively less high than image
h = dm.h - safety;
w = static_cast<int>(round(image_ratio * h));
} else { // screen relatively less wide than image
w = dm.w - safety;
h = static_cast<int>(round(w / image_ratio));
}
}
set_size(w, h);
}