Rendering Text with SDL_ttf

Rendering Multi-line Text

How do I handle multi-line text rendering in SDL2 with SDL_ttf?

3D art representing computer programming

Rendering multi-line text in SDL2 with SDL_ttf requires a bit of extra work, as SDL_ttf doesn't have a built-in function for this. We need to split the text into lines, render each line separately, and then combine them onto a single surface. Here's how we can accomplish this:

  1. Split the text into lines
  2. Render each line as a separate surface
  3. Calculate the total height needed for all lines
  4. Create a new surface large enough to hold all lines
  5. Blit each line onto the new surface
  6. Clean up individual line surfaces

Let's implement this step-by-step:

#include <SDL.h>
#include <SDL_ttf.h>

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

SDL_Surface* RenderMultilineText(
  TTF_Font* font, const std::string& text,
  SDL_Color color, int lineSpacing = 0) {
  // Split the text into lines
  std::vector<std::string> lines;
  std::istringstream stream(text);
  std::string line;
  while (std::getline(stream, line)) {
    lines.push_back(line);
  }

  // Render each line
  std::vector<SDL_Surface*> lineSurfaces;
  int totalHeight = 0;
  int maxWidth = 0;

  for (const auto& line : lines) {
    SDL_Surface* lineSurface =
      TTF_RenderUTF8_Blended(
        font, line.c_str(), color);
    if (!lineSurface) {
      std::cout << "Failed to render line: " <<
        TTF_GetError() << '\n';
      // Clean up previously rendered surfaces
      for (auto surface : lineSurfaces) {
        SDL_FreeSurface(surface);
      }
      return nullptr;
    }
    lineSurfaces.push_back(lineSurface);
    totalHeight += lineSurface->h + lineSpacing;
    maxWidth = std::max(maxWidth,
                        lineSurface->w);
  }

  // Adjust total height for last line's spacing
  if (!lineSurfaces.empty()) {
    totalHeight -= lineSpacing;
  }

  // Create the final surface
  SDL_Surface* resultSurface =
    SDL_CreateRGBSurfaceWithFormat(
      0, maxWidth, totalHeight, 32,
      lineSurfaces[0]->format->format);

  if (!resultSurface) {
    std::cout <<
      "Failed to create result surface: " <<
      SDL_GetError() << '\n';
    for (auto surface : lineSurfaces) {
      SDL_FreeSurface(surface);
    }
    return nullptr;
  }

  // Blit each line onto the final surface
  int yPos = 0;
  for (auto lineSurface : lineSurfaces) {
    SDL_Rect dstRect = {
      0, yPos, lineSurface->w, lineSurface->h};
    SDL_BlitSurface(lineSurface, nullptr,
                    resultSurface, &dstRect);
    yPos += lineSurface->h + lineSpacing;
    SDL_FreeSurface(lineSurface);
  }

  return resultSurface;
}

int main() {
  SDL_Init(SDL_INIT_VIDEO);
  TTF_Init();

  TTF_Font* font = TTF_OpenFont(
    "path/to/font.ttf", 24);
  if (!font) {
    std::cout << "Failed to load font: " <<
      TTF_GetError() << '\n';
    return 1;
  }

  std::string multilineText =
    "This is a multi-line text example.\n"
    "It demonstrates how to render\n"
    "multiple lines using SDL2 and SDL_ttf.";

  SDL_Color textColor = {255, 255, 255, 255};
  // White
  SDL_Surface* textSurface =
    RenderMultilineText(font, multilineText,
                        textColor, 5);

  if (textSurface) {
    // Use textSurface in your rendering loop
    // ...

    SDL_FreeSurface(textSurface);
  }

  TTF_CloseFont(font);
  TTF_Quit();
  SDL_Quit();

  return 0;
}

This implementation allows you to render multi-line text with custom line spacing. The RenderMultilineText() function takes the font, text, color, and optional line spacing as parameters.

To use this in your Text class from the lesson, you could modify the CreateSurface() method to use RenderMultilineText() instead of TTF_RenderUTF8_Blended(). This would allow your Text objects to handle multi-line text automatically.

Remember to handle newline characters ('\n') in your text input appropriately. In this example, we use std::getline() to split the text into lines, which automatically handles '\n' characters.

By adjusting the lineSpacing parameter, you can control the vertical distance between lines, allowing for more compact or spacious text layouts as needed for your application.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 62 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved