1 module d2d.font.ttftext; 2 3 version(BindSDL_TTF): 4 5 import d2d; 6 7 import std.algorithm : max; 8 9 /// Implementation containing text drawable functions using a TTF font. Nice for static texts, slow for dynamic texts. 10 class TTFText : RectangleShape, IText 11 { 12 private: 13 float _scale = 1.0f; 14 string _text = ""; 15 TTFFont _font; 16 bool _multiline = false; 17 18 public: 19 /// Creates an empty ttf text 20 this(TTFFont font) 21 { 22 _font = font; 23 texture = new Texture(); 24 texture.create(0, 0, []); 25 } 26 27 /// Gets the scale in percent. 28 override @property float scale() 29 { 30 return _scale; 31 } 32 33 /// Sets the scale in percent. 34 override @property void scale(float value) 35 { 36 _scale = value; 37 } 38 39 /// Gets the text. 40 override @property string text() 41 { 42 return _text; 43 } 44 45 /// Modifies the text. 46 override @property void text(string value) 47 { 48 if (_text != value) 49 { 50 _text = value; 51 redraw(); 52 } 53 } 54 55 /// Returns if this text should be rendered multiline. 56 @property bool multiline() 57 { 58 return _multiline; 59 } 60 61 /// Sets if this text should be rendered multiline. 62 @property void multiline(bool value) 63 { 64 if (_multiline != value) 65 { 66 _multiline = value; 67 redraw(); 68 } 69 } 70 71 /// Should get called automatically when something changed. 72 void redraw() 73 { 74 Bitmap bmp; 75 if (_multiline) 76 { 77 string[] lines = text.split('\n'); 78 int maxWidth = 0; 79 foreach (string line; lines) 80 { 81 int w, h; 82 TTF_SizeText(_font.handle, line.toStringz(), &w, &h); 83 maxWidth = max(w, maxWidth); 84 } 85 bmp = Bitmap.fromSurface(TTF_RenderUTF8_Blended_Wrapped(_font.handle, text.toStringz(), Color.White.sdl_color, maxWidth)); 86 } 87 else 88 { 89 bmp = Bitmap.fromSurface(TTF_RenderUTF8_Blended(_font.handle, text.toStringz(), Color.White.sdl_color)); 90 } 91 if (!bmp.valid) 92 throw new Exception(cast(string) TTF_GetError().fromStringz()); 93 texture.recreateFromBitmap(bmp, "Blended Text: \"" ~ text ~ "\""); 94 size = vec2(texture.width, texture.height); 95 create(); 96 } 97 98 override void draw(IRenderTarget target, ShaderProgram shader = null) 99 { 100 matrixStack.push(); 101 matrixStack.top = matrixStack.top * mat4.scaling(_scale, _scale, 1); 102 super.draw(target, shader); 103 matrixStack.pop(); 104 } 105 106 override @property bool valid() 107 { 108 return super.valid; 109 } 110 111 override void dispose() 112 { 113 super.dispose(); 114 } 115 }