1 | /* |
2 | src/label.cpp -- Text label with an arbitrary font, color, and size |
3 | |
4 | NanoGUI was developed by Wenzel Jakob <wenzel.jakob@epfl.ch>. |
5 | The widget drawing code is based on the NanoVG demo application |
6 | by Mikko Mononen. |
7 | |
8 | All rights reserved. Use of this source code is governed by a |
9 | BSD-style license that can be found in the LICENSE.txt file. |
10 | */ |
11 | |
12 | #include <nanogui/label.h> |
13 | #include <nanogui/theme.h> |
14 | #include <nanogui/opengl.h> |
15 | #include <nanogui/serializer/core.h> |
16 | |
17 | NAMESPACE_BEGIN(nanogui) |
18 | |
19 | Label::Label(Widget *parent, const std::string &caption, const std::string &font, int fontSize) |
20 | : Widget(parent), mCaption(caption), mFont(font) { |
21 | if (mTheme) { |
22 | mFontSize = mTheme->mStandardFontSize; |
23 | mColor = mTheme->mTextColor; |
24 | } |
25 | if (fontSize >= 0) mFontSize = fontSize; |
26 | } |
27 | |
28 | void Label::setTheme(Theme *theme) { |
29 | Widget::setTheme(theme); |
30 | if (mTheme) { |
31 | mFontSize = mTheme->mStandardFontSize; |
32 | mColor = mTheme->mTextColor; |
33 | } |
34 | } |
35 | |
36 | Vector2i Label::preferredSize(NVGcontext *ctx) const { |
37 | if (mCaption == "" ) |
38 | return Vector2i::Zero(); |
39 | nvgFontFace(ctx, mFont.c_str()); |
40 | nvgFontSize(ctx, fontSize()); |
41 | if (mFixedSize.x() > 0) { |
42 | float bounds[4]; |
43 | nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_TOP); |
44 | nvgTextBoxBounds(ctx, mPos.x(), mPos.y(), mFixedSize.x(), mCaption.c_str(), nullptr, bounds); |
45 | return Vector2i(mFixedSize.x(), bounds[3] - bounds[1]); |
46 | } else { |
47 | nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE); |
48 | return Vector2i( |
49 | nvgTextBounds(ctx, 0, 0, mCaption.c_str(), nullptr, nullptr) + 2, |
50 | fontSize() |
51 | ); |
52 | } |
53 | } |
54 | |
55 | void Label::draw(NVGcontext *ctx) { |
56 | Widget::draw(ctx); |
57 | nvgFontFace(ctx, mFont.c_str()); |
58 | nvgFontSize(ctx, fontSize()); |
59 | nvgFillColor(ctx, mColor); |
60 | if (mFixedSize.x() > 0) { |
61 | nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_TOP); |
62 | nvgTextBox(ctx, mPos.x(), mPos.y(), mFixedSize.x(), mCaption.c_str(), nullptr); |
63 | } else { |
64 | nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE); |
65 | nvgText(ctx, mPos.x(), mPos.y() + mSize.y() * 0.5f, mCaption.c_str(), nullptr); |
66 | } |
67 | } |
68 | |
69 | void Label::save(Serializer &s) const { |
70 | Widget::save(s); |
71 | s.set("caption" , mCaption); |
72 | s.set("font" , mFont); |
73 | s.set("color" , mColor); |
74 | } |
75 | |
76 | bool Label::load(Serializer &s) { |
77 | if (!Widget::load(s)) return false; |
78 | if (!s.get("caption" , mCaption)) return false; |
79 | if (!s.get("font" , mFont)) return false; |
80 | if (!s.get("color" , mColor)) return false; |
81 | return true; |
82 | } |
83 | |
84 | NAMESPACE_END(nanogui) |
85 | |