Files
openglplayground/font.cc

42 lines
820 B
C++

#include <cassert>
#include <SDL2/SDL_ttf.h>
#include "common.hh"
#include "texture.hh"
#include "font.hh"
Font::Font(std::string const& filename, unsigned ptsize)
: font_{nullptr}
{
assert(TTF_WasInit());
font_ = TTF_OpenFont(filename.c_str(), ptsize);
if(!font_)
throw TTFException{};
}
Font::~Font()
{
if(font_)
TTF_CloseFont(font_);
}
Texture2D Font::render(std::string const& text, bool fast) const {
SDL_Surface *surf;
if(fast)
surf = TTF_RenderUTF8_Solid(font_, text.c_str(), SDL_Color{255, 255, 255, 255});
else
surf = TTF_RenderUTF8_Blended(font_, text.c_str(), SDL_Color{255, 255, 255, 255});
if(!surf)
throw TTFException{};
try {
Texture2D ret{surf};
SDL_FreeSurface(surf);
return ret;
} catch(...) {
SDL_FreeSurface(surf);
throw;
}
}