1 module d2d.font.ttffont; 2 3 version(BindSDL_TTF): 4 5 import d2d; 6 7 import std.algorithm : max; 8 9 /// Implementation for SDL_ttf. 10 class TTFFont : IFont 11 { 12 private: 13 TTF_Font* _handle; 14 15 public: 16 ~this() 17 { 18 dispose(); 19 } 20 21 /// Handle to underlying `TTF_Font*` handle. 22 @property TTF_Font* handle() 23 { 24 return _handle; 25 } 26 27 /// Loads the font from a file. 28 override void load(string file, int sizeInPt) 29 { 30 _handle = TTF_OpenFont(file.toStringz(), sizeInPt); 31 if (!valid) 32 throw new Exception(cast(string) TTF_GetError().fromStringz()); 33 } 34 35 /// Returns if `_handle` is not `null`. 36 override @property bool valid() 37 { 38 return _handle !is null; 39 } 40 41 /// Deallocates memory and invalidates this. 42 override void dispose() 43 { 44 if (valid) 45 { 46 TTF_CloseFont(_handle); 47 _handle = null; 48 } 49 } 50 51 /// Renders a string to an IText. 52 override IText render(string text, float scale = 1.0f) 53 { 54 TTFText ret = new TTFText(this); 55 ret.text = text; 56 ret.scale = scale; 57 return ret; 58 } 59 60 /// Renders a multiline string to an IText. 61 override IText renderMultiline(string text, float scale = 1.0f) 62 { 63 TTFText ret = new TTFText(this); 64 ret.text = text; 65 ret.scale = scale; 66 ret.multiline = true; 67 return ret; 68 } 69 70 /// Returns the line height of this font. 71 @property float lineHeight() 72 { 73 return TTF_FontHeight(_handle); 74 } 75 76 /// Returns the dimensions of a string with this font. 77 override vec2 measureText(string text, float scale = 1.0f) 78 { 79 int w, h; 80 TTF_SizeUTF8(_handle, text.toStringz(), &w, &h); 81 return vec2(w * scale, h * scale); 82 } 83 84 /// Returns the dimensions of a multiline string with this font. 85 override vec2 measureTextMultiline(string text, float scale = 1.0f) 86 { 87 string[] lines = text.split('\n'); 88 int w, h; 89 foreach (string line; lines) 90 { 91 int lw, lh; 92 TTF_SizeText(_handle, line.toStringz(), &lw, &lh); 93 w = max(w, lw); 94 h += lh; 95 } 96 return vec2(w * scale, h * scale); 97 } 98 }