2021-12-16 14:30:32 +01:00

98 lines
2.3 KiB
C++

#include "KFont.h"
#include "KTexture.h"
namespace KapitanGame
{
KFont::KFont()
= default;
KFont::~KFont()
{
Free();
}
KFont::KFont(KFont&& other) noexcept : Font(other.Font)
{
other.Font = nullptr;
}
KFont& KFont::operator=(KFont&& other) noexcept
{
Font = other.Font;
other.Font = nullptr;
return *this;
}
bool KFont::LoadFromFile(const std::string& path, const int ptSize)
{
bool success = true;
Font = TTF_OpenFont(path.c_str(), ptSize);
if (Font == nullptr)
{
printf("Failed to load %s font! SDL_ttf Error: %s\n", path.c_str(), TTF_GetError());
success = false;
}
return success;
}
void KFont::Free()
{
if (Font != nullptr)
{
TTF_CloseFont(Font);
Font = nullptr;
}
}
KTexture KFont::GetTextTexture(const std::string& text, const SDL_Color textColor, SDL_Renderer* renderer) const
{
KTexture texture;
SDL_Surface* textSurface = TTF_RenderText_Blended(Font, text.c_str(), textColor);
if (textSurface == nullptr)
{
printf("Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError());
}
else
{
texture.LoadFromSurface(textSurface, renderer);
SDL_FreeSurface(textSurface);
}
return texture;
}
KTexture KFont::GetTextWithOutlineTexture(const std::string& text, const SDL_Color fgColor, const SDL_Color bgColor,
const int outlineSize, SDL_Renderer* renderer) const
{
KTexture texture;
const int originalOutlineSize = TTF_GetFontOutline(Font);
if (SDL_Surface* fgSurface = TTF_RenderText_Blended(Font, text.c_str(), fgColor); fgSurface == nullptr)
{
printf("Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError());
}
else
{
TTF_SetFontOutline(Font, outlineSize);
SDL_Surface* bgSurface = TTF_RenderText_Blended(Font, text.c_str(), bgColor);
TTF_SetFontOutline(Font, originalOutlineSize);
if (bgSurface == nullptr)
{
printf("Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError());
}
else
{
SDL_Rect rect = { outlineSize, outlineSize, fgSurface->w, fgSurface->h };
/* blit text onto its outline */
SDL_SetSurfaceBlendMode(fgSurface, SDL_BLENDMODE_BLEND);
SDL_BlitSurface(fgSurface, nullptr, bgSurface, &rect);
texture.LoadFromSurface(bgSurface, renderer);
SDL_FreeSurface(bgSurface);
}
SDL_FreeSurface(fgSurface);
}
return texture;
}
}