• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

Custom Linebreak function

S

Sake_v2

Guest
I'm aware that GM:S has a draw_text_ext function that automatically draws a string adding a linebreak if it exceeds the maximum width, this is exactly what I need, but I need to return the string, so I can know its width/height exactly.

To know the string_height/number of lines I tried dividing the string_width by the maximum width, which would return the number of lines but this doesn't take the spaces into account, leading to imprecision.

I created a custom linebreak function that works, but the problem is that it takes more than 10x the time that the draw_text_ext function takes to draw. In a shorter string, the draw_text_ext functions took about 33 microseconds to run, while my function took 123. With longer strings, my function is taking about 600 microseconds to run.

How to make it less performance heavy, closer to the draw_text_ext function?


Code:
///string_set_linebreak(string,width,font)
var _maxwidth, _str, _font;
_str = argument0;
_maxwidth = argument1;
_font = argument2;

draw_set_font(_font);

if string_width(_str) <= _maxwidth
{
    return _str;
}

var pos, length, width, spacefound, previouspos;
pos = 1;
length = string_length(_str);
width = 0;
spacefound = 1;
previouspos = 1;

while(pos < length)
{
    var currentpos;
    currentpos = string_char_at(_str,pos);

    if currentpos == " "
    {
        spacefound = pos;
    }
    width += string_width(currentpos);
    
    if width > _maxwidth && spacefound > 1
    {
        
        var inserton;
        inserton = spacefound+1;
        
        if spacefound == previouspos
        {
            inserton = pos;
        }
        _str = string_insert("#",_str,inserton);
        width = 0;
        pos = inserton+1;
        previouspos = spacefound;
    } else {
        pos++;
    }
}

show_debug_message("string returned: "+string(_str));

return _str;
 

chamaeleon

Member
I'm aware that GM:S has a draw_text_ext function that automatically draws a string adding a linebreak if it exceeds the maximum width, this is exactly what I need, but I need to return the string, so I can know its width/height exactly.
Won't string_width_ext() and string_height_ext() do for your needs?
 
Top