memononen / fontstash

Light-weight online font texture atlas builder

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Newline wrapping

Nairou opened this issue · comments

Any plans to add text wrapping (on newline)? Specifically, in the text iteration functions used by NanoVG.

I've started to look into it, and got the simple (left-align) case working, but it gets complicated with right/center alignment. I'm not yet familiar enough with fons__decutf8() to scan for newlines without it crashing. I'd like to get your thoughts/plans before pursuing it further.

I think the simplest way to do that for now is to first break the text into lines and then draw each line at a time. Something like this:

char* start = text;
char* end = text;
while (*end) {
    if (*end == ‘\r’ || *end == ‘\n’) {
        fonsDrawText(fs, x,y, start, end, NULL);
        y += lineHeight;
        end++;
        // handle cr-lf, and lf-cr too.
        if (*end == ‘\r’ || *end == ‘\n’) str++;
        start = end;
    } else {
        str++;
    }
}
if (start != end)
    fonsDrawText(fs, x,y, start, end, NULL);

The above should work with UTF-8 too as well as the iterator.

While that looks great, my instinct is to wrap it in a function, so I can call a single function to render text as before. Maybe fonsDrawTextMulti()? Or are you wanting to keep this sort of thing out of the library?

Though, the bigger issue in my mind is implementing it in such a way that NanoVG can use it. Since NanoVG uses the fons iterator functions, not fonsDrawText, it would either require a change in both, or this wrapper function might need to exist within NanoVG instead. Since NanoVG uses the iterators, I don't know if there is a clean separation as far as where multi-line text support should be added.

I think it might be better to have the multi line draw functionality be build on top of fontstash, that is, in nanovg. Please add an issue there so that it won't get overlooked.

For the time being, you should be able to build similar wrapper on top of nanovg. Proper vertical align for all cases can be a little tricky to implement.

Good point, I didn't even think of vertical alignment and multiple lines. I've opened the NanoVG issue, and your wrapper idea should work fine for now. Thanks!