From 6bf0b64f248d143b53f4740f34009396bb05d49e Mon Sep 17 00:00:00 2001 From: Gleb Mazovetskiy Date: Thu, 20 Feb 2020 10:22:44 +0900 Subject: [PATCH] Support transparent images --- sdlutils.cpp | 21 ++++++++++++++++++++- viewer.cpp | 20 +++++++++++++++----- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/sdlutils.cpp b/sdlutils.cpp index 6ec0e47..752de54 100755 --- a/sdlutils.cpp +++ b/sdlutils.cpp @@ -34,6 +34,22 @@ SDL_Surface *SDL_utils::loadImage(const std::string &p_filename) return l_img2; } +static void AsciiToLower(std::string *s) +{ + for (char &c : *s) + if (c >= 'A' && c <= 'Z') + c -= ('Z' - 'z'); +} + +static std::string GetFileExtension(const std::string &name) { + const auto dot_pos = name.rfind('.'); + if (dot_pos == std::string::npos) + return ""; + std::string ext = name.substr(dot_pos + 1); + AsciiToLower(&ext); + return ext; +} + SDL_Surface *SDL_utils::loadImageToFit(const std::string &p_filename, int fit_w, int fit_h) { // Load image @@ -57,7 +73,10 @@ SDL_Surface *SDL_utils::loadImageToFit(const std::string &p_filename, int fit_w, target_h *= PPU_Y; SDL_Surface *l_img2 = zoomSurface(l_img, static_cast(target_w) / l_img->w, static_cast(target_h) / l_img->h, SMOOTHING_ON); SDL_FreeSurface(l_img); - SDL_Surface *l_img3 = SDL_DisplayFormat(l_img2); + + const std::string ext = GetFileExtension(p_filename); + const bool supports_alpha = ext != "xcf" && ext != "jpg" && ext != "jpeg"; + SDL_Surface *l_img3 = supports_alpha ? SDL_DisplayFormatAlpha(l_img2) : SDL_DisplayFormat(l_img2); SDL_FreeSurface(l_img2); return l_img3; } diff --git a/viewer.cpp b/viewer.cpp index 9398464..53c59d3 100755 --- a/viewer.cpp +++ b/viewer.cpp @@ -49,11 +49,7 @@ CViewer::CViewer(const std::string &p_fileName): // Create background image m_background = SDL_utils::createImage(SCREEN_WIDTH, SCREEN_HEIGHT * PPU_Y, SDL_MapRGB(Globals::g_screen->format, COLOR_BG_1)); { - SDL_Rect l_rect; - l_rect.x = 0; - l_rect.y = 0; - l_rect.w = SCREEN_WIDTH; - l_rect.h = Y_LIST * PPU_Y; + SDL_Rect l_rect = {0, 0, SCREEN_WIDTH, Y_LIST * PPU_Y}; SDL_FillRect(m_background, &l_rect, SDL_MapRGB(m_background->format, COLOR_BORDER)); } // Print title @@ -79,6 +75,20 @@ CViewer::CViewer(const std::string &p_fileName): if (m_image != nullptr) { m_mode = IMAGE; + + // Transparency grid background. + constexpr int kTransparentBgRectSize = 10; + const Uint32 colors[2] = { + SDL_MapRGB(m_background->format, 240, 240, 240), + SDL_MapRGB(m_background->format, 155, 155, 155), + }; + int i = 0; + for (int y = Y_LIST; y < SCREEN_HEIGHT; y += kTransparentBgRectSize, ++i) { + for (int x = 0; x < SCREEN_WIDTH; x += kTransparentBgRectSize, ++i) { + SDL_Rect rect = {x, y * PPU_Y, kTransparentBgRectSize, kTransparentBgRectSize * PPU_Y}; + SDL_FillRect(m_background, &rect, colors[i % 2]); + } + } } else {