Skip to content

Instantly share code, notes, and snippets.

@DougEdey
Forked from alvesvaren/text_wrap.cpp
Created March 19, 2026 02:07
Show Gist options
  • Select an option

  • Save DougEdey/1d0e8b4db03201bc5810093cdda7290b to your computer and use it in GitHub Desktop.

Select an option

Save DougEdey/1d0e8b4db03201bc5810093cdda7290b to your computer and use it in GitHub Desktop.
Text wrapping for the esphome display api, with Color support
#include <vector>
#include <string>
#include <sstream>
#include "esphome/components/display/display_buffer.h"
#include "esphome/components/font/font.h"
#include "text_wrap.h"
using namespace esphome;
using namespace esphome::display;
using namespace esphome::font;
int wrap_text(Display* it, int x, int y, const char* text, Font* font, TextAlign align, float line_height, std::optional<esphome::Color> color) {
int space_x1, space_y1, space_width, space_height;
it->get_text_bounds(x, y, " ", font, align, &space_x1, &space_y1, &space_width, &space_height);
std::vector<std::string> words;
std::stringstream ss(text);
std::string word;
while (std::getline(ss, word, ' ')) {
words.push_back(word);
}
int line_x = x;
int line_y = y;
int word_x1, word_y1, word_width, word_height;
std::string line;
// Iterate through the words and wrap them
for (const auto& w : words) {
it->get_text_bounds(line_x, line_y, w.c_str(), font, align, &word_x1, &word_y1, &word_width, &word_height);
if (line_x + word_width >= it->get_width()) {
if (color.has_value()) {
it->printf(x, line_y, font, color.value(), COLOR_OFF, align, "%s", line.c_str());
} else {
it->printf(x, line_y, font, align, "%s", line.c_str());
}
line_y += static_cast<int>(word_height * line_height);
line_x = x;
line.clear();
}
line += w;
line_x += word_width + space_width;
if (!line.empty() && &w != &words.back()) {
line += " ";
}
}
if (!line.empty()) {
if (color.has_value()) {
it->printf(x, line_y, font, color.value(), COLOR_OFF, align, "%s", line.c_str());
} else {
it->printf(x, line_y, font, align, "%s", line.c_str());
}
}
return line_y + static_cast<int>(word_height * line_height);
}
#pragma once
#include "esphome/components/display/display_buffer.h"
#include "esphome/components/font/font.h"
// #include "esphome/color.h"
int wrap_text(
esphome::display::Display* it, int x, int y,
const char* text, esphome::font::Font* font,
esphome::display::TextAlign align, float line_height,
std::optional<esphome::Color> color = std::nullopt
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment