idea4good/GuiLite

wrap text needed in draw_string_in_rect()

sbradwrk opened this issue · 2 comments

draw_string_in_rect() has align_type argument but does not have an in-built option to wrap (clip) text. Instead of allowing text to run out of the rectangle, it should be able to 'insert' a new line each time until the bottom of the rectangle and then also stop at the bottom of the rectangle

If an existing example / workaround exists, please advise. I see get_str_size() is available

put into GuiLite source would look a bit different, but this is a starting point if it helps. inserting \n was a nonstarter

void draw_string_in_wrapped_rect(c_surface* surface, int z_order, std::string instr, c_rect rect, const void* font, unsigned int font_color, unsigned int bg_color, unsigned int align_type = ALIGN_LEFT)
{
    int w = 0, h = 0;
    c_word::get_str_size( instr.c_str(), font, w, h );

    const int width  = rect.width();
    const int height = rect.height();

    if( w <= width )
    {
        c_word::draw_string_in_rect( surface, z_order, instr.c_str(), rect, font, font_color, bg_color, align_type );
        return;
    }

    int x = 0, y = 0, rowy = 0;
    int est_chars_per_line = ( (float)width / w * instr.size() );
    int nrows              = std::max( 1, std::min( 1 + ( w - 1 ) / width, ( height + h ) / h ) );

    for( int row = 0, pos = 0; row < nrows; row++, pos += est_chars_per_line, rowy += h )
    {
        std::string linestr = instr.substr( pos, est_chars_per_line );
        const char *line    = linestr.c_str();
        c_word::fontOperator->get_string_pos( (const void *)line, (const LATTICE_FONT_INFO *)font, rect, align_type, x, y );
        c_word::draw_string(
            surface, z_order, (const void *)line, rect.m_left + x, rect.m_top + rowy + y, font, font_color, bg_color );
    }
}

also worth looking at existing code

while (*s)
		{
			s += get_utf8_code(s, utf8_code);
			offset += draw_single_char(surface, z_order, utf8_code, (x + offset), y, (const LATTICE_FONT_INFO*)font, font_color, bg_color);
		}

if char == \n you could increase a y offset and reset x