1 /// module containing the text UI element 2 module ysge.ui.text; 3 4 import std.string; 5 import ysge.project; 6 7 class Text : UIElement { 8 private string text; 9 private SDL_Texture* texture; 10 SDL_Color colour; 11 Vec2!int pos; 12 float scale = 1.0; 13 14 /// copies this UI element to a new class instance 15 Text CreateCopy() { 16 auto ret = new Text(); 17 18 ret.SetText(text); 19 ret.colour = colour; 20 ret.pos = pos; 21 ret.scale = scale; 22 23 return ret; 24 } 25 26 /// sets the text that is rendered 27 void SetText(string newText) { 28 if (text != newText) { 29 texture = null; 30 } 31 32 text = newText; 33 } 34 35 /// re-renders the text 36 void Reload(Project parent) { 37 texture = null; 38 CreateTexture(parent); 39 } 40 41 /// returns the size in pixels of the text 42 Vec2!int GetTextSize(Project project) { 43 Vec2!int ret; 44 45 CreateTexture(project); 46 SDL_QueryTexture(texture, null, null, &ret.x, &ret.y); 47 ret = Vec2!int( 48 cast(int) (ret.CastTo!float().x * scale), 49 cast(int) (ret.CastTo!float().x * scale) 50 ); 51 return ret; 52 } 53 54 private void CreateTexture(Project project) { 55 if (texture is null) { 56 SDL_Surface* surface = TTF_RenderText_Solid( 57 project.font, toStringz(text), colour 58 ); 59 60 if (surface is null) { 61 throw new ProjectException("Failed to render text"); 62 } 63 64 texture = SDL_CreateTextureFromSurface(project.renderer, surface); 65 66 if (texture is null) { 67 throw new ProjectException("Failed to create text texture"); 68 } 69 } 70 } 71 72 override bool HandleEvent(Project project, SDL_Event e) { 73 return false; 74 } 75 76 override void Render(Project project) { 77 CreateTexture(project); 78 79 SDL_Rect textBox; 80 textBox.x = pos.x; 81 textBox.y = pos.y; 82 83 SDL_QueryTexture(texture, null, null, &textBox.w, &textBox.h); 84 85 textBox.w = cast(int) ((cast(float) textBox.w) * scale); 86 textBox.h = cast(int) ((cast(float) textBox.h) * scale); 87 88 SDL_RenderCopy(project.renderer, texture, null, &textBox); 89 } 90 }