Skip to content

Instantly share code, notes, and snippets.

@Twinklebear
Created August 18, 2012 21:33
Show Gist options
  • Select an option

  • Save Twinklebear/3390025 to your computer and use it in GitHub Desktop.

Select an option

Save Twinklebear/3390025 to your computer and use it in GitHub Desktop.
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <stdexcept>
#include <string>
#include <iostream>
if (TTF_Init() == -1){
std::cout << TTF_GetError() << std::endl;
return 2;
}
SDL_Texture* RenderText(std::string message, std::string fontFile,
SDL_Color color, int fontSize)
{
//Open the font
TTF_Font *font = nullptr;
font = TTF_OpenFont(fontFile.c_str(), fontSize);
if (font == nullptr)
throw std::runtime_error("Failed to load font: " + fontFile + TTF_GetError());
//Render the message to an SDL_Surface, as that's what TTF_RenderText_X returns
SDL_Surface *surf = TTF_RenderText_Blended(font, message.c_str(), color);
SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surf);
//Clean up unneeded stuff
SDL_FreeSurface(surf);
TTF_CloseFont(font);
return texture;
}
SDL_Texture *image = nullptr;
try {
SDL_Color color = { 255, 255, 255 };
image = RenderText("TTF fonts are cool!", "../res/Lesson6/SourceSansPro-Regular.ttf",
color, 64);
}
catch (const std::runtime_error &e){
std::cout << e.what() << std::endl;
return 4;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment