Font.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // ----------------------------------------------------------------
  2. // From Game Programming in C++ by Sanjay Madhav
  3. // Copyright (C) 2017 Sanjay Madhav. All rights reserved.
  4. //
  5. // Released under the BSD License
  6. // See LICENSE in root directory for full details.
  7. // ----------------------------------------------------------------
  8. #include "Font.h"
  9. #include "Texture.h"
  10. #include <vector>
  11. #include "Game.h"
  12. Font::Font(class Game* game)
  13. :mGame(game)
  14. {
  15. }
  16. Font::~Font()
  17. {
  18. }
  19. bool Font::Load(const std::string& fileName)
  20. {
  21. // We support these font sizes
  22. std::vector<int> fontSizes = {
  23. 8, 9,
  24. 10, 11, 12, 14, 16, 18,
  25. 20, 22, 24, 26, 28,
  26. 30, 32, 34, 36, 38,
  27. 40, 42, 44, 46, 48,
  28. 52, 56,
  29. 60, 64, 68,
  30. 72
  31. };
  32. for (auto& size : fontSizes)
  33. {
  34. TTF_Font* font = TTF_OpenFont(fileName.c_str(), size);
  35. if (font == nullptr)
  36. {
  37. SDL_Log("Failed to load font %s in size %d", fileName.c_str(), size);
  38. return false;
  39. }
  40. mFontData.emplace(size, font);
  41. }
  42. return true;
  43. }
  44. void Font::Unload()
  45. {
  46. for (auto& font : mFontData)
  47. {
  48. TTF_CloseFont(font.second);
  49. }
  50. }
  51. Texture* Font::RenderText(const std::string& textKey,
  52. const Vector3& color /*= Color::White*/,
  53. int pointSize /*= 24*/)
  54. {
  55. Texture* texture = nullptr;
  56. // Convert to SDL_Color
  57. SDL_Color sdlColor;
  58. sdlColor.r = static_cast<Uint8>(color.x * 255);
  59. sdlColor.g = static_cast<Uint8>(color.y * 255);
  60. sdlColor.b = static_cast<Uint8>(color.z * 255);
  61. sdlColor.a = 255;
  62. // Find the font data for this point size
  63. auto iter = mFontData.find(pointSize);
  64. if (iter != mFontData.end())
  65. {
  66. TTF_Font* font = iter->second;
  67. const std::string& actualText = mGame->GetText(textKey);
  68. // Draw this to a surface (blended for alpha)
  69. SDL_Surface* surf = TTF_RenderUTF8_Blended(font, actualText.c_str(), sdlColor);
  70. if (surf != nullptr)
  71. {
  72. // Convert from surface to texture
  73. texture = new Texture();
  74. texture->CreateFromSurface(surf);
  75. SDL_FreeSurface(surf);
  76. }
  77. }
  78. else
  79. {
  80. SDL_Log("Point size %d is unsupported", pointSize);
  81. }
  82. return texture;
  83. }