PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Multiple lines w/ text.

Is there any way to display text with multiple lines? I tried the typical \n for newline, but it doesn't work.

Thanks in advance.
Not inherently to GapiDraw. You'll need to break the text yourself programmatically and place each line accordingly.
Ah, alright. Thanks.
Bah *logs in*
Give me a day, I have to write this code too so I'll post it here when I get it done.
I wrote this and it seems to do the trick.

It uses std::string of _TCHAR, so as long as you pass in _T("text") it will work fine.

It breaks the text into words by space, and draws words at a time. If a word doesn't fit on a line, it starts a new line.

A single leading space is removed on new lines, but other spaces are preserved. As long as you only separate words by one space it will look fine.

If a single word cannot fit on a new line, it stops drawing. It also stops drawing when it reaches the bottom of the area.

Code:

typedef std::string<_TCHAR> tstring;

void
drawText(
CGapiSurface& surface,
CGapiBitmapFont& font,
const RECT& kRect,
const tstring& ks)
{
if (ks.empty())
{
return;
}

const int knLineHeight = font.GetHeight();

int nBeginPos = 0;
int nEndPos = ks.find(_T(" "));

tstring sWord = ks.substr(0, nEndPos);
DWORD nWordWidth;

int nX = kRect.left;
int nY = kRect.top;

if (kRect.bottom < nY + knLineHeight)
{
// The first line doesn't fit, so abort.
return;
}

while (true)
{
// Get the width of the word.
font.GetStringWidth(sWord.c_str(), &nWordWidth);

if (nX + nWordWidth <= kRect.right)
{
// The word fits on this line so draw it.
surface.DrawText(
nX,
nY,
sWord.c_str(),
&font,
0,
NULL,
0,
NULL);

// Advance the position.
nX += nWordWidth;

if (nEndPos == tstring::npos)
{
// We have drawn all the words.
break;
}
else
{
// Advance to the next word.
nBeginPos = nEndPos;
nEndPos = ks.find(_T(" "), nEndPos + 1);
sWord = ks.substr(nBeginPos, nEndPos - nBeginPos);
}
}
else
{
// The word doesn't fit on this line.

if (nX == kRect.left)
{
// This is already a new line, so abort.
break;
}
else
{
// Make a new line.
nY += knLineHeight;

if (kRect.bottom < nY + knLineHeight)
{
// The new line doesn't fit, so abort.
break;
}

// Prepare the new line by removing the leading space.
nX = kRect.left;
sWord = sWord.erase(sWord.begin());
}
}
}
}
Nice. My implementation was just going to be something simple; search for \n and then move y coords down to the next line.
Just noticed that typedef should be

Code:

typedef std::basic_string<_TCHAR> tstring;
How about this:
Code:

bool guiTextbox::drawText( CGapiSurface* pSurface ,
CGapiBitmapFont* pFont ,
long lx ,
long ly ,
TCHAR* pszString,
dword dwFlags,
bool bMultiline )

{
// Hardcoded for this example

long lFontHeight = 7;
long lLineSpacing = 4;

// Get the first line - reading up to the carrage return
TCHAR* pszTok = NULL;

// If the caller is requesting multiline functionality, then do so using strtok to
// separate the lines using the carrage return
if( bMultiline )
{
pszTok = _tcstok( pszString, _T("\n") );

// While there is a valid string....
while( pszTok )
{
// Draw the text unto the surface.
if( pSurface->DrawText( lx, ly, pszTok, pFont, dwFlags, NULL, 0UL, NULL ) != S_OK )
return false;

// Increment to the next line
ly += (lFontHeight + lLineSpacing);

// Use the strtok function to obtain the next line
pszTok = _tcstok( NULL, _T("\n") );
}
}
else
{
// Otherwise, just draw the string normally.
if( pSurface->DrawText( lx, ly, pszString, pFont, dwFlags, NULL, 0UL, NULL ) != S_OK )
return false;
}

return true;
}


This takes a bunch of text and for each 0x13 (\n) carriage return it will move to the next line and blit it. It's important to note that the text's X and Y coordinate have already been formatted to handle the various alignment the text can have.

You also may notice that there is no checking to see if the line fits or not and nor is it really needed. This is because if the text does not fit within the boxed area, then it will be chopped off (or simply not rendered). Seeing this, the person who made the text would have to go back and fix up the text (or increase the area where the text goes into) since we would never accept a final product that had missing text within a check box.

Anyways, this is very simple and it works when you add carriage returns to your text. Also note, that the argument 'bMultiline' - if its false, then it will all be blitted on a single line.
I should also add that the code above is meant for a static window, one that is not dynamicially resizable. If that is your aim, then you would have to check word for word and handle all the re-formatting within the function.
Layre5150 wrote:I should also add that the code above is meant for a static window, one that is not dynamicially resizable. If that is your aim, then you would have to check word for word and handle all the re-formatting within the function.


That's pretty much the method I use in Warlords II for string handling, but I use a pipe ( | ) delimiter instead of looking for embedded control characters. An ascii delimiter makes it easier for the user (and me!) to modify the text to suit their needs - a godsend when you want to localize to a different language. This allows me to put several segments of text on a single line in an ascii text file.

I haven't tried Marc's method of on-the-fly formatting yet. I think it is a fantastic method if you have a scrollable text box like in RPGs.
I use the tilde (~) character as my delimiter. I find that's even less useful than the pipe character in actual text :)

Don't really know why I felt the need to tell anyone this...
My method works fine for laying out text, but for scrolling, you might want more beef in your data structures. For example, you might want to use a method similar to mine to lay out the text into lines before hand. You could do this by copying the text into a line-oriented data structure, but an even better way is to just make note of where the newlines are in a markup data structure.

Glad to be of help.
One thing to be considered is not to "overload" your function with functionality for every eventuality. If your goal is to have a control that handles window resizing then it will need to handle text re-formatting.

However, if the goal is to have a textbox that blits single/multi lines of text with scrolling capabilities then all that is required is just that.

The code that I added could be fixed to scroll with only the smallest amount of changes.

However, having code that meets every condition yet not every condition ends up being met, then it's just the same as not having the code in the first place.

All in all, you want to have code that's robust but you don't want to over-do it.
What you say is mostly true.

Your code still tokenizes every line for every drawing when it need not do so. It also relies on newlines embedded in the text.

Another way is to tokenize once (using newlines in the file, or a width, or whatever) and store those as character indices, not newline characters. Then, when drawing, you need not recompute the indices, but merely draw the substrings from one index to the next as separate lines.

This is not really more complicated than what you have. And that approach lends itself well to resizing, because you need not alter your text, just the indices of where new lines are.

The function I wrote above will not scroll, and it isn't efficient because it also does computation for every draw that it need only do once. But it's sufficient for drawing text into a rectangle without manually predetermining where all the newlines should be. That's ideal during development, even if for release you change it to a static layout by figuring out where to place new lines.

The nice thing about these forums is that readers have so many different solutions to choose from. It never hurts to see different approaches. Also, they are commented so they make a good starting point even if you want to alter them into something different.
I noticed that both the methods above rely on word length, however my font is not a fixed-width font so sometimes sentences with more "W" and "M" get clipped on the screen. Is there a way we can bind the word lengths with the actual "letter" width?
egarayblas wrote:I noticed that both the methods above rely on word length, however my font is not a fixed-width font so sometimes sentences with more "W" and "M" get clipped on the screen. Is there a way we can bind the word lengths with the actual "letter" width?


You can preprocess your text by walking through it 'measuring' each letter until you pass your maximum allowable length. You would just need to keep track of each full word (or syllable if you want to hyphenate) and fall back to the last full word if you pass your maximum line length.

CGapiBitmapFont::GetCharWidth and CGapiBitmapFont::GetStringWidth are the methods for this.
Whoa! Thanks GR! I didn't know about that one. This reminds me that I should be more resourceful next time. :) My current project is really getting me focused more on gameplay and level design that I sometimes forget about the GD documentation.
Erick, the code I wrote above also uses those functions, so should serve as a good example. That's exactly what it does: fall back to the last word that fit in the desired area.
I know this topic is old, but it's still relevant. I looked through GapiDraw docs and release history, and found no information on updated text formatting (I was hoping it was native to GapiDraw by now). Since it wasn't, I decided to write my own.

I realize there are a few implementations here, but unfortunately none were as flexible as I wanted them to be. mlepage's implementation didn't support regular line breaks '\n', and the other implementation didn't support word wrap.

I decided to make a Text object which supported all of this, yet remained efficient.

Flexibility and features include:

- Word wrapping.
- Support for line breaks. '\n'
- Text padding.
- Line spacing.
- Text alignment (Left, Center, Right). NOTE: Center alignment centers both horizontally and vertically.

As far I'm aware, this includes pretty much all of the features you need. But what about performance? Performance should be good. This is how it works:

Using the Text object, you specify the format of your text (this includes the actual text, padding, spacing, alignment, and so on). When you're done, you make a single call to Text::Format(). The Text::Format() function goes through the text and formats it accordingly, adding '|' characters (you can change it to whatever you want) for word wrapping, and leaving regular line breaks '\n' alone. Later, if you want to reformat your text, you set the parameters and call Text::Format() once again. It'll remove the old word wrap characters '|' and reformat the text.

The point is, you only format the text when necessary, NOT every frame. Basically you are preformatting your text so it can efficiently be drawn.

The Text::Draw() function is simple and efficient. All it does is looks for word wrap and line break characters, and draws the text line by line, NOT word by word.

Here are the functions and helper functions discussed. Below that are the source files.

NOTE: When using multiple line breaks '\n\n' it doesn't work exactly as expected. If you want to use more than one line break, you'll need to add a space between them, like so: '\n \n' This will format properly.

Code:

void Text::Format()
{
// Assume the text has been formatted before,
// thus all line seperators need to be removed.
this->RemoveLineSeperators();

CGapiBitmapFont* pFont = this->GetDrawingFont();
tstring_t::size_type index = 0;
DWORD charSpacing = 0;
DWORD wordWidth = 0;
DWORD lineWidth = 0;
DWORD numOfLines = 0;
DWORD padding = m_padding << 1;

DWORD spaceWidth;
pFont->GetCharWidth(_T(" ")[0], &spaceWidth);

tstring_t strWord;
strWord.reserve(TEXT_WORD_LENGTH);

tstring_t::size_type lineBeginPos = 0, lineEndPos, wordBeginPos = 0, wordEndPos;
lineEndPos = m_text.find(_T("\n")); // First line.

// Go through all the lines in the text.
while (true)
{
// Move to new line.
numOfLines++;
lineWidth = padding;

// First word in line.
wordEndPos = m_text.find(_T(" "), lineBeginPos);

// Go through all the words in the line.
while (true)
{
// Get size of the entire word.
strWord = m_text.substr(wordBeginPos, wordEndPos - wordBeginPos);
pFont->GetStringWidth(strWord.c_str(), &wordWidth);

// Check for word spacing.
if (lineWidth > padding) {
lineWidth += spaceWidth;
}

// Check word wrap.
lineWidth += wordWidth;
if (lineWidth > (DWORD) m_region.cx) {
if (wordBeginPos != 0) {
// Mark line seperation.
m_text[wordBeginPos - 1] = TEXT_LINE_SEPERATOR[0];
}

// Move to new line and add the word to it.
numOfLines++;
lineWidth = padding + wordWidth;
}

if (wordEndPos == tstring_t::npos || wordEndPos > lineEndPos) {
break; // No more words on this line.
}

// Move to next word.
wordBeginPos = wordEndPos + 1;
wordEndPos = m_text.find(_T(" "), wordBeginPos);
}

if (lineEndPos == tstring_t::npos) {
break; // No more lines to be found.
}

// Move to next line.
lineBeginPos = lineEndPos + 1;
lineEndPos = m_text.find(_T("\n"), lineBeginPos);
}

// Properly align text to the text region.
this->AlignText(numOfLines, pFont->GetHeight());
}

void Text::RemoveLineSeperators()
{
tstring_t::size_type pos;
pos = m_text.find(TEXT_LINE_SEPERATOR); // First line seperator.

// Go until no line seperators are found.
while (pos != tstring_t::npos)
{
m_text[pos] = _T(" ")[0]; // Insert space where seperator is at.

// Get next seperator.
pos = m_text.find(TEXT_LINE_SEPERATOR, pos + 1);
}
}

void Text::AlignText(DWORD numOfLines, DWORD fontHeight)
{
switch(m_alignment)
{
case GDDRAWTEXT_LEFT:
{
m_alignPos.x = m_padding;
m_alignPos.y = m_padding;
break;
}
case GDDRAWTEXT_CENTER:
{
m_alignPos.x = m_region.cx >> 1;

DWORD textHeight = numOfLines * (fontHeight + m_lineSpacing) - m_lineSpacing;
if (textHeight > m_region.cy - (m_padding << 1)) {
// Text won't event fit, so don't align y axis.
m_alignPos.y = m_padding;
}
else {
m_alignPos.y = (m_region.cy >> 1) - (textHeight >> 1);
}

break;
}
case GDDRAWTEXT_RIGHT:
{
m_alignPos.x = m_region.cx - m_padding;
m_alignPos.y = m_padding;
break;
}
default: // Should never happen.
break;
}
}


Code:

void Text::Draw(CGapiSurface* pBuffer, LONG x, LONG y) const
{
if (m_text.empty()) {
return; // No reason to draw an empty string.
}

CGapiBitmapFont* pFont = this->GetDrawingFont();
DWORD fontHeight = pFont->GetHeight();

// Adjust for padding.
LONG xPos = x + m_alignPos.x;
LONG yPos = y + m_alignPos.y;

// Draw text line by line. It should already be formatted,
// so drawing should be as efficient as possible.

tstring_t strTok(m_text);
TCHAR* pLineTok = NULL;
const TCHAR pTokens[] = { _T("\n")[0], TEXT_LINE_SEPERATOR[0], NULL };

pLineTok = _tcstok(const_cast<TCHAR*>(strTok.c_str()), pTokens); // First line.

while (pLineTok != NULL && (yPos + (LONG) fontHeight) < (y + m_region.cy - (LONG) m_padding))
{
// Draw line.
if (pBuffer->DrawText(xPos, yPos, pLineTok, pFont, m_alignment, NULL, NULL, NULL) != S_OK) {
return;
};

// Move to next line.
pLineTok = _tcstok(NULL, pTokens);
yPos += fontHeight + m_lineSpacing;
}
}
Attachments:
GDText.zip (3 KB)
Noticed a bug today in my Text class. Apparently if you specify NULL for the alignment (which it does in the constructor as default), then the padding won't work. To fix, change

m_alignment = NULL;

to

m_alignment = GDDRAWTEXT_LEFT;

in the constructor.
Hi! If anyone has an example directly from his project how to use this great script, could you please post it here, because there is few things I can not understand and make it run properly.
8O
You mean GapiDraw in all it's glory doesn't inherantly have functions for handling text with multiple lines? :?: