Root/src/font.h

1// Original font class was replaced by an SDL_ttf based one by Paul Cercueil.
2// License: GPL version 2 or later.
3
4#ifndef FONT_H
5#define FONT_H
6
7#include <SDL_ttf.h>
8#include <memory>
9#include <string>
10
11class Surface;
12
13/**
14 * Wrapper around a TrueType or other FreeType-supported font.
15 * The wrapper is valid even if the font couldn't be loaded, but in that case
16 * nothing will be drawn.
17 */
18class Font {
19public:
20    enum HAlign { HAlignLeft, HAlignRight, HAlignCenter };
21    enum VAlign { VAlignTop, VAlignBottom, VAlignMiddle };
22
23    /**
24     * Returns a newly created Font object for the default font.
25     */
26    static std::unique_ptr<Font> defaultFont();
27
28    Font(const std::string &path, unsigned int size);
29    ~Font();
30
31    std::string wordWrap(const std::string &text, int width);
32
33    int getTextWidth(const std::string& text);
34    int getTextHeight(const std::string& text);
35
36    int getLineSpacing()
37    {
38        return lineSpacing;
39    }
40
41    /**
42     * Draws a text on a surface in this font.
43     * @return The width of the text in pixels.
44     */
45    int write(Surface& surface,
46                const std::string &text, int x, int y,
47                HAlign halign = HAlignLeft, VAlign valign = VAlignTop);
48
49private:
50    Font(TTF_Font *font);
51
52    std::string wordWrapSingleLine(const std::string &text,
53                size_t start, size_t end, int width);
54
55    /**
56     * Draws a single line of text on a surface in this font.
57     * @return The width of the text in pixels.
58     */
59    int writeLine(Surface& surface, std::string const& text,
60                int x, int y, HAlign halign, VAlign valign);
61
62    TTF_Font *font;
63    int lineSpacing;
64};
65
66#endif /* FONT_H */
67

Archive Download this file



interactive