emilib
text_paint.hpp
1 // By Emil Ernerfeldt 2014-2016
2 // LICENSE:
3 // This software is dual-licensed to the public domain and under the following
4 // license: you are granted a perpetual, irrevocable license to copy, modify,
5 // publish, and distribute this file as you see fit.
6 // HISTORY:
7 // Created in 2014-12 for Ghostel
8 // Cleaned up as separate library 2016-02
9 
10 /*
11 Library for drawing colored, multiline strings on iOS and OSX.
12 
13 Requires Foundation and CoreText on both iOS and OSX.
14 Requires UIKit on iOS.
15 Requires AppKit on OSX.
16 */
17 
18 #pragma once
19 
20 #include <limits>
21 #include <string>
22 #include <vector>
23 
24 namespace text_paint {
25 
26 struct Vec2 { float x, y; };
27 struct RGBAf { float r, g, b, a; };
28 
29 enum class TextAlign
30 {
31  LEFT,
32  CENTER,
33  RIGHT
34 };
35 
38 {
39  struct ColorRange
40  {
41  RGBAf color;
42  size_t length_bytes;
43  };
44 
45  struct FontRange
46  {
47  size_t begin, end;
48  std::string font;
49  };
50 
51  std::string utf8;
52  std::vector<ColorRange> colors;
53  std::vector<FontRange> fonts;
54 
55  AttributeString() {}
56 
57  explicit AttributeString(const std::string& str, RGBAf color = {1, 1, 1, 1})
58  {
59  append(str, color);
60  }
61 
62  void append(const std::string& str, RGBAf color = {1, 1, 1, 1})
63  {
64  auto pre_size = utf8.size();
65  utf8 += str;
66  colors.push_back(ColorRange{color, utf8.size() - pre_size});
67  }
68 
70  void set_font_range(size_t begin, size_t end, std::string font)
71  {
72  fonts.emplace_back(FontRange{begin, end, std::move(font)});
73  }
74 };
75 
76 struct TextInfo
77 {
78  std::string font = "Noteworthy-Light";
79  float font_size = 22;
80  TextAlign alignment = TextAlign::LEFT;
81 
82  // Use max_size.x to set a max width for wrapping the text to.
83  Vec2 max_size = {std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity()};
84 };
85 
90 Vec2 text_size(const TextInfo& ti, const AttributeString& str);
91 
98 void draw_text(
99  uint8_t* bytes, size_t width, size_t height, bool rgba,
100  const Vec2& pos, const TextInfo& ti, const AttributeString& str);
101 
103 bool test();
104 
105 } // namespace text_paint
Definition: text_paint.hpp:26
Definition: text_paint.hpp:27
Definition: text_paint.hpp:76
Definition: text_paint.hpp:24
void set_font_range(size_t begin, size_t end, std::string font)
Set different font for byte range [begin, end)
Definition: text_paint.hpp:70
Definition: text_paint.hpp:39
Multiline text where ranges can be colored differently.
Definition: text_paint.hpp:37
size_t length_bytes
Use this color for this many bytes of utf8.
Definition: text_paint.hpp:42
Definition: text_paint.hpp:45