Sfoglia il codice sorgente

Fix '?' on end of non-ASCII text in typing animation

Evgeniy Parfenyuk 2 settimane fa
parent
commit
4dab6d0f25
3 ha cambiato i file con 40 aggiunte e 4 eliminazioni
  1. 0 1
      src/main.c
  2. 37 1
      src/text_utils.h
  3. 3 2
      src/ui/text_box.c

+ 0 - 1
src/main.c

@@ -49,7 +49,6 @@ int main(void)
     "reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla "
     "pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa "
     "qui officia deserunt mollit anim id est laborum.");
-    
     while (!WindowShouldClose())
     {
         float dt = GetFrameTime();

+ 37 - 1
src/text_utils.h

@@ -39,7 +39,8 @@ static char *WrapText(Font font, const char *text, float fontSize,
         char savedChar = result[i + 1];
         result[i + 1] = '\0';
 
-        Vector2 size = MeasureTextEx(font, &result[currentLineStartIdx], fontSize, spacing);
+        Vector2 size = MeasureTextEx(font, &result[currentLineStartIdx],
+                                     fontSize, spacing);
         
         result[i + 1] = savedChar;
 
@@ -67,6 +68,41 @@ static char *WrapText(Font font, const char *text, float fontSize,
     return result;
 }
 
+static int GetUtf8ByteLength(const char *text, int count)
+{
+    if (!text || count <= 0) return 0;
+
+    int byte_len = 0;
+    int glyph_count = 0;
+
+    while (text[byte_len] != '\0' && glyph_count < count)
+    {
+        unsigned char c = (unsigned char)text[byte_len];
+        int current_char_len = 1;
+
+        if (c >= 0xF0)      current_char_len = 4; // Emoji (unsupported) 
+        else if (c >= 0xE0) current_char_len = 3; // CJK
+        else if (c >= 0xC0) current_char_len = 2; // Cyryllic
+        else                current_char_len = 1; // ASCII
+
+        for (int i = 0; i < current_char_len; i++) {
+            if (text[byte_len + i] == '\0') {
+                return byte_len;
+            }
+        }
+
+        // Skipping emojis...
+        if (current_char_len == 4) {
+            byte_len += 4; 
+            continue; 
+        }
+
+        byte_len += current_char_len;
+        glyph_count++;
+    }
+
+    return byte_len;
+}
 
 #endif
 

+ 3 - 2
src/ui/text_box.c

@@ -103,10 +103,11 @@ void TextBoxDraw(const TextBox *tb)
         DrawRectangleLinesEx(tb->rect, tb->border_thickness, tb->border_color);
     if (tb->wrapped_text && tb->wrapped_text[0] != '\0')
     {
-        int max_chars = (tb->typing_speed > 0) 
+        int max_glyphs = (tb->typing_speed > 0)
             ? (int)(tb->timer * tb->typing_speed)
             : (int)strlen(tb->wrapped_text);
-        const char *visible_text = TextSubtext(tb->wrapped_text, 0, max_chars);
+        int byte_len = GetUtf8ByteLength(tb->wrapped_text, max_glyphs);
+        const char *visible_text = TextSubtext(tb->wrapped_text, 0, byte_len);
 
         Vector2 text_pos = {
             tb->rect.x + tb->padding,