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?
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;