I have a menu class which will be taking care of basically all of the non-play part of a game I'm making. I'm trying to cut down on having to load many textures, so I've used polymorphism to have my sprite class re-use textures that have been previously loaded. I tried to the same with my text class but ran into some issues....
This is the basic constructor, as you can see it will create a font by loading in the font from a file. I feel like that is a waste of resources. I would like to have another constructor which re-uses the same file. The problem is, by passing a previous font as an argument, I lose the ability to decide what size the font will be.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
text::text(std::string passed_message, TTF_Font* passed_font, int size, SDL_Color f_passed_color, SDL_Color b_passed_color, SDL_Renderer* passed_renderer)
{
//do stuff
the_font = passed_font; /* issue here */
/* Now int size has become irrelevant */
text_surface = TTF_RenderText_Solid(the_font, passed_message.c_str(),
background_Color);
text_texture = SDL_CreateTextureFromSurface(renderer, text_surface);
SDL_FreeSurface(text_surface);
//location stuff
}
How can I edit the current existing font's size without loading a new font? Or using TTF_OpenFont()?
#pragma once
#include <assert.h>
#include <SDL_ttf.h>
#include <map>
class SDL_Font
{
std::string FontLocation;
std::map<int, TTF_Font*> FontSizes;
public:
//Save the path to the TTF file and do some error checking string cant be empty
bool Load(const std::string& FileLocation) override
{
FontLocation = FileLocation;
if (FileLocation == "")
assert(false);
returntrue;
}
// loads and returns a TTF_Font.
// looks in the map if the font already exists if not create a new font with the requested size
TTF_Font* GetFont(int FontSize)
{
std::map<int, TTF_Font*>::iterator it;
it = FontSizes.find(FontSize);
if (it != FontSizes.end())
return it->second;
else
{
TTF_Font* mFont = TTF_OpenFont(FontLocation.c_str(), FontSize);
FontSizes.insert(std::pair<int, TTF_Font*>(FontSize, mFont));
return mFont;
}
}
~SDL_Font()
{
//i think i should delete the loaded fonts
}
};
//Render the text to a SDL_Texture with the requested size.
void TextBox::RenderTexture()
{
if (mText != "" && mFont != nullptr)
{
if (mTextTexture != nullptr)
SDL_DestroyTexture(mTextTexture);//get rid of old texture(text)
//Text Texture is made into a surface here
SDL_Surface* mTextSurface = TTF_RenderText_Solid(mFont->GetFont(mFontSize),
mText.c_str(),
mColor);
std::string temp = TTF_GetError(); //the text can not be emty
mTextTextureSize.Width = mTextSurface->w;
mTextTextureSize.Height = mTextSurface->h;
//now the surface becomes a SDL_Texture i can now draw it to screen.
mTextTexture = SDL_CreateTextureFromSurface(TheScreen::Instance().GetRenderer(), mTextSurface);
SDL_FreeSurface(mTextSurface);
}
}