Created
February 25, 2020 18:12
-
-
Save lighth7015/47a9a4d7c6d20c7a0cfc2c0f5218a9da to your computer and use it in GitHub Desktop.
Justified label control
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <FL/Fl_Box.H> | |
class TextLabel: public Fl_Box { | |
LayoutEngine engine; | |
std::string text; | |
public: | |
TextLabel( std::string& text, uint32_t x, uint32_t y, uint32_t height, uint32_t width) | |
: text(text) | |
, Fl_Box( x, y, width, height, text.c_str()) | |
{ | |
// Empty constructor. | |
} | |
void draw() override { | |
uint32_t height = fl_height() * 1.3, i = 0; | |
uint32_t top = y() + height, start = x(); | |
uint32_t space = (fl_width(" ") * 1.24), | |
width = w(), | |
left = x(); | |
Fl_Font faceName(fl_font()); | |
Fl_Fontsize faceSize(fl_size()); | |
fl_font(labelfont(), labelsize()); | |
auto document = engine.parse(text); | |
fl_color(FL_BLACK); | |
uint32_t pxBoxWidth(((x() + width) * 2) + space), pTextWidth = 0; | |
uint32_t pCalcWidth(((fl_width(" ") / 1.5) * width) + ( (int) ( width / 1.5 ) - 2 )); | |
typedef std::vector<std::pair<uint32_t, std::string>> StringList; | |
std::vector<std::pair<uint32_t, StringList>> collection; | |
StringList item; | |
for (std::string word : document.content) { | |
uint32_t pTextLength = fl_width(word.c_str()), | |
id = item.size() + 1; | |
if ( start + ( fl_width(word.c_str()) + space ) >= pCalcWidth ) { | |
start = left; | |
item.push_back(std::make_pair( id, word )); | |
collection.push_back(std::make_pair( collection.size(), item )); | |
item.clear(); | |
} | |
else { | |
start += fl_width(word.c_str()) + space; | |
item.push_back(std::make_pair( id, word )); | |
} | |
} | |
for ( std::pair<uint32_t, StringList> iterator : collection ) { | |
uint32_t spaceLeft(pCalcWidth), | |
calcSlice(pCalcWidth / iterator.second.size()), | |
textWidth( 0 ); | |
start = left; | |
for (std::pair<uint32_t, std::string> entry: iterator.second ) { | |
uint32_t textLength(fl_width(entry.second.c_str())); | |
if (textLength > textWidth) { | |
textWidth = textLength + space; | |
} | |
} | |
for (std::pair<uint32_t, std::string> entry: iterator.second ) { | |
if ((spaceLeft - calcSlice) > 0) { | |
spaceLeft -= calcSlice; | |
} | |
fl_draw( entry.second.c_str(), start, top ); | |
uint32_t pCalcSpace = pCalcWidth / iterator.second.size(); | |
printf("Free space: %s = %d/%d = %d ( %d, %d )\n", | |
entry.second, pCalcWidth, iterator.second.size(), pCalcSpace, | |
spaceLeft, calcSlice ); | |
start += textWidth; | |
} | |
top += height; | |
} | |
fl_font(faceName, faceSize); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment