text_rectangle_bounds.c 12 KB

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