/
ofxTextInputFieldFontRenderer.h
108 lines (80 loc) · 2.76 KB
/
ofxTextInputFieldFontRenderer.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/** ___ ___ ___ ___ ___
* /__/\ / /\ / /\ _____ / /\ /__/|
* | |::\ / /::\ / /::| / /::\ / /::\ | |:|
* | |:|:\ / /:/\:\ / /:/:| / /:/\:\ / /:/\:\ | |:|
* __|__|:|\:\ / /:/~/::\ / /:/|:|__ / /:/~/::\ / /:/ \:\ __|__|:|
* /__/::::| \:\ /__/:/ /:/\:\ /__/:/ |:| /\ /__/:/ /:/\:| /__/:/ \__\:\ /__/::::\____
* \ \:\~~\__\/ \ \:\/:/__\/ \__\/ |:|/:/ \ \:\/:/~/:/ \ \:\ / /:/ ~\~~\::::/
* \ \:\ \ \::/ | |:/:/ \ \::/ /:/ \ \:\ /:/ |~~|:|~~
* \ \:\ \ \:\ | |::/ \ \:\/:/ \ \:\/:/ | |:|
* \ \:\ \ \:\ | |:/ \ \::/ \ \::/ | |:|
* \__\/ \__\/ |__|/ \__\/ \__\/ |__|/
*
* Description:
*
* ofxTextInputFieldFontRenderer.h, created by Marek Bereza on 14/08/2013.
*/
namespace ofxTextInput {
class FontRenderer {
public:
virtual ~FontRenderer() {}
virtual void drawString(string text, int x, int y) = 0;
virtual float getLineHeight() = 0;
virtual float stringWidth(const string &str) = 0;
virtual bool isBitmapFont() { return false; }
// this gets the cursor position (in characters) based on an x coordinate.
int getPosition(const string &str, int x) {
float lastW = 0;
for(int i = 0; i < str.size(); i++) {
float w = this->stringWidth(str.substr(0, i+1));
if(x<lastW + (w-lastW)/2.f) {
return i;
}
lastW = w;
}
return str.size();
}
};
class TypedFontRenderer: public FontRenderer {
public:
OFX_TEXTFIELD_FONT_RENDERER *renderer;
TypedFontRenderer(OFX_TEXTFIELD_FONT_RENDERER *renderer) {
this->renderer = renderer;
}
void drawString(string text, int x, int y) {
renderer->drawString(text, x, y);
}
float getLineHeight() {
return renderer->getLineHeight();
}
float spacesWidth(const string &str) {
if(str.size()>0 && str[str.size()-1]==' ') {
return renderer->getSpaceSize()*renderer->getSize();
}
return 0;
}
float stringWidth(const string &str) {
return renderer->stringWidth(str) + spacesWidth(str) + 3;
}
};
class BitmapFontRenderer: public FontRenderer {
public:
virtual bool isBitmapFont() { return true; }
void drawString(string text, int x, int y) {
ofDrawBitmapString(text, x, y);
}
float getLineHeight() {
return 8.f*1.725f;
}
float stringWidth(const string &str) {
int w = 0;
for(int i = 0; i < str.size(); i++) {
if(str[i]=='\t')
w += 8 - (w % 8);
else
w ++;
}
return w*8;
}
};
};