text_rectangle_bounds.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /*******************************************************************************************
  2. *
  3. * raylib [text] example - Draw text inside a rectangle
  4. *
  5. * This example has been created using raylib 2.3 (www.raylib.com)
  6. * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
  7. *
  8. * Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5)
  9. *
  10. * Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
  11. *
  12. ********************************************************************************************/
  13. #include "raylib.h"
  14. static void DrawTextBoxed(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint); // Draw text using font inside rectangle limits
  15. static void DrawTextBoxedSelectable(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint, int selectStart, int selectLength, Color selectTint, Color selectBackTint); // Draw text using font inside rectangle limits with support for text selection
  16. // Main entry point
  17. int main(void)
  18. {
  19. // Initialization
  20. //--------------------------------------------------------------------------------------
  21. const int screenWidth = 800;
  22. const int screenHeight = 450;
  23. InitWindow(screenWidth, screenHeight, "raylib [text] example - draw text inside a rectangle");
  24. const char text[] = "Text cannot escape\tthis container\t...word wrap also works when active so here's \
  25. a long text for testing.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod \
  26. tempor incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet risus nullam eget felis eget.";
  27. bool resizing = false;
  28. bool wordWrap = true;
  29. Rectangle container = { 25.0f, 25.0f, screenWidth - 50.0f, screenHeight - 250.0f };
  30. Rectangle resizer = { container.x + container.width - 17, container.y + container.height - 17, 14, 14 };
  31. // Minimum width and heigh for the container rectangle
  32. const float minWidth = 60;
  33. const float minHeight = 60;
  34. const float maxWidth = screenWidth - 50.0f;
  35. const float maxHeight = screenHeight - 160.0f;
  36. Vector2 lastMouse = { 0.0f, 0.0f }; // Stores last mouse coordinates
  37. Color borderColor = MAROON; // Container border color
  38. Font font = GetFontDefault(); // Get default system font
  39. SetTargetFPS(60); // Set our game to run at 60 frames-per-second
  40. //--------------------------------------------------------------------------------------
  41. // Main game loop
  42. while (!WindowShouldClose()) // Detect window close button or ESC key
  43. {
  44. // Update
  45. //----------------------------------------------------------------------------------
  46. if (IsKeyPressed(KEY_SPACE)) wordWrap = !wordWrap;
  47. Vector2 mouse = GetMousePosition();
  48. // Check if the mouse is inside the container and toggle border color
  49. if (CheckCollisionPointRec(mouse, container)) borderColor = Fade(MAROON, 0.4f);
  50. else if (!resizing) borderColor = MAROON;
  51. // Container resizing logic
  52. if (resizing)
  53. {
  54. if (IsMouseButtonReleased(MOUSE_BUTTON_LEFT)) resizing = false;
  55. float width = container.width + (mouse.x - lastMouse.x);
  56. container.width = (width > minWidth)? ((width < maxWidth)? width : maxWidth) : minWidth;
  57. float height = container.height + (mouse.y - lastMouse.y);
  58. container.height = (height > minHeight)? ((height < maxHeight)? height : maxHeight) : minHeight;
  59. }
  60. else
  61. {
  62. // Check if we're resizing
  63. if (IsMouseButtonDown(MOUSE_BUTTON_LEFT) && CheckCollisionPointRec(mouse, resizer)) resizing = true;
  64. }
  65. // Move resizer rectangle properly
  66. resizer.x = container.x + container.width - 17;
  67. resizer.y = container.y + container.height - 17;
  68. lastMouse = mouse; // Update mouse
  69. //----------------------------------------------------------------------------------
  70. // Draw
  71. //----------------------------------------------------------------------------------
  72. BeginDrawing();
  73. ClearBackground(RAYWHITE);
  74. DrawRectangleLinesEx(container, 3, borderColor); // Draw container border
  75. // Draw text in container (add some padding)
  76. DrawTextBoxed(font, text, (Rectangle){ container.x + 4, container.y + 4, container.width - 4, container.height - 4 }, 20.0f, 2.0f, wordWrap, GRAY);
  77. DrawRectangleRec(resizer, borderColor); // Draw the resize box
  78. // Draw bottom info
  79. DrawRectangle(0, screenHeight - 54, screenWidth, 54, GRAY);
  80. DrawRectangleRec((Rectangle){ 382.0f, screenHeight - 34.0f, 12.0f, 12.0f }, MAROON);
  81. DrawText("Word Wrap: ", 313, screenHeight-115, 20, BLACK);
  82. if (wordWrap) DrawText("ON", 447, screenHeight - 115, 20, RED);
  83. else DrawText("OFF", 447, screenHeight - 115, 20, BLACK);
  84. DrawText("Press [SPACE] to toggle word wrap", 218, screenHeight - 86, 20, GRAY);
  85. DrawText("Click hold & drag the to resize the container", 155, screenHeight - 38, 20, RAYWHITE);
  86. EndDrawing();
  87. //----------------------------------------------------------------------------------
  88. }
  89. // De-Initialization
  90. //--------------------------------------------------------------------------------------
  91. CloseWindow(); // Close window and OpenGL context
  92. //--------------------------------------------------------------------------------------
  93. return 0;
  94. }
  95. //--------------------------------------------------------------------------------------
  96. // Module functions definition
  97. //--------------------------------------------------------------------------------------
  98. // Draw text using font inside rectangle limits
  99. static void DrawTextBoxed(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint)
  100. {
  101. DrawTextBoxedSelectable(font, text, rec, fontSize, spacing, wordWrap, tint, 0, 0, WHITE, WHITE);
  102. }
  103. // Draw text using font inside rectangle limits with support for text selection
  104. static void DrawTextBoxedSelectable(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint, int selectStart, int selectLength, Color selectTint, Color selectBackTint)
  105. {
  106. int length = TextLength(text); // Total length in bytes of the text, scanned by codepoints in loop
  107. float textOffsetY = 0; // Offset between lines (on line break '\n')
  108. float textOffsetX = 0.0f; // Offset X to next character to draw
  109. float scaleFactor = fontSize/(float)font.baseSize; // Character rectangle scaling factor
  110. // Word/character wrapping mechanism variables
  111. enum { MEASURE_STATE = 0, DRAW_STATE = 1 };
  112. int state = wordWrap? MEASURE_STATE : DRAW_STATE;
  113. int startLine = -1; // Index where to begin drawing (where a line begins)
  114. int endLine = -1; // Index where to stop drawing (where a line ends)
  115. int lastk = -1; // Holds last value of the character position
  116. for (int i = 0, k = 0; i < length; i++, k++)
  117. {
  118. // Get next codepoint from byte string and glyph index in font
  119. int codepointByteCount = 0;
  120. int codepoint = GetCodepoint(&text[i], &codepointByteCount);
  121. int index = GetGlyphIndex(font, codepoint);
  122. // NOTE: Normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f)
  123. // but we need to draw all of the bad bytes using the '?' symbol moving one byte
  124. if (codepoint == 0x3f) codepointByteCount = 1;
  125. i += (codepointByteCount - 1);
  126. float glyphWidth = 0;
  127. if (codepoint != '\n')
  128. {
  129. glyphWidth = (font.glyphs[index].advanceX == 0) ? font.recs[index].width*scaleFactor : font.glyphs[index].advanceX*scaleFactor;
  130. if (i + 1 < length) glyphWidth = glyphWidth + spacing;
  131. }
  132. // NOTE: When wordWrap is ON we first measure how much of the text we can draw before going outside of the rec container
  133. // We store this info in startLine and endLine, then we change states, draw the text between those two variables
  134. // and change states again and again recursively until the end of the text (or until we get outside of the container).
  135. // When wordWrap is OFF we don't need the measure state so we go to the drawing state immediately
  136. // and begin drawing on the next line before we can get outside the container.
  137. if (state == MEASURE_STATE)
  138. {
  139. // TODO: There are multiple types of spaces in UNICODE, maybe it's a good idea to add support for more
  140. // Ref: http://jkorpela.fi/chars/spaces.html
  141. if ((codepoint == ' ') || (codepoint == '\t') || (codepoint == '\n')) endLine = i;
  142. if ((textOffsetX + glyphWidth) > rec.width)
  143. {
  144. endLine = (endLine < 1)? i : endLine;
  145. if (i == endLine) endLine -= codepointByteCount;
  146. if ((startLine + codepointByteCount) == endLine) endLine = (i - codepointByteCount);
  147. state = !state;
  148. }
  149. else if ((i + 1) == length)
  150. {
  151. endLine = i;
  152. state = !state;
  153. }
  154. else if (codepoint == '\n') state = !state;
  155. if (state == DRAW_STATE)
  156. {
  157. textOffsetX = 0;
  158. i = startLine;
  159. glyphWidth = 0;
  160. // Save character position when we switch states
  161. int tmp = lastk;
  162. lastk = k - 1;
  163. k = tmp;
  164. }
  165. }
  166. else
  167. {
  168. if (codepoint == '\n')
  169. {
  170. if (!wordWrap)
  171. {
  172. textOffsetY += (font.baseSize + font.baseSize/2)*scaleFactor;
  173. textOffsetX = 0;
  174. }
  175. }
  176. else
  177. {
  178. if (!wordWrap && ((textOffsetX + glyphWidth) > rec.width))
  179. {
  180. textOffsetY += (font.baseSize + font.baseSize/2)*scaleFactor;
  181. textOffsetX = 0;
  182. }
  183. // When text overflows rectangle height limit, just stop drawing
  184. if ((textOffsetY + font.baseSize*scaleFactor) > rec.height) break;
  185. // Draw selection background
  186. bool isGlyphSelected = false;
  187. if ((selectStart >= 0) && (k >= selectStart) && (k < (selectStart + selectLength)))
  188. {
  189. DrawRectangleRec((Rectangle){ rec.x + textOffsetX - 1, rec.y + textOffsetY, glyphWidth, (float)font.baseSize*scaleFactor }, selectBackTint);
  190. isGlyphSelected = true;
  191. }
  192. // Draw current character glyph
  193. if ((codepoint != ' ') && (codepoint != '\t'))
  194. {
  195. DrawTextCodepoint(font, codepoint, (Vector2){ rec.x + textOffsetX, rec.y + textOffsetY }, fontSize, isGlyphSelected? selectTint : tint);
  196. }
  197. }
  198. if (wordWrap && (i == endLine))
  199. {
  200. textOffsetY += (font.baseSize + font.baseSize/2)*scaleFactor;
  201. textOffsetX = 0;
  202. startLine = endLine;
  203. endLine = -1;
  204. glyphWidth = 0;
  205. selectStart += lastk - k;
  206. k = lastk;
  207. state = !state;
  208. }
  209. }
  210. textOffsetX += glyphWidth;
  211. }
  212. }