Word wrapping

Just starting out? Need help? Post your questions and find answers here.
wombats
Enthusiast
Enthusiast
Posts: 720
Joined: Thu Dec 29, 2011 5:03 pm

Word wrapping

Post by wombats »

Hi,

I'm trying to create algorithms to wrap text into maximum width. I'd like to be able to do both word and character. I'm not sure I'm doing this right. It adds an unwanted line at the beginning if the rectangle is too small for any word. And would I handle wrapping based on characters in a similar way?

Code: Select all

EnableExplicit

#TEXT_WRAP_CHARACTER = 0
#TEXT_WRAP_WORD = 1

Structure FontCharacter
  id.i
  w.i
  h.i
EndStructure

Global spaceWidth.i = 20
Global NewList characters.FontCharacter()

Define i
For i = 65 To 90
  AddElement(characters())
  characters()\id = i
  characters()\w = 32
  characters()\h = 32
Next

Procedure SplitText(text.s, mode.i, maxWidth.i, List lines.s())
  Protected currentLine.s, lineWidth.i, i, c, word.s, wordWidth.i,
            char.s
  ClearList(lines())
  currentLine.s = ""
  lineWidth.i = 0
  Select mode
    Case #TEXT_WRAP_WORD
      For i = 1 To CountString(text, " ") + 1
        wordWidth = 0
        word = StringField(text, i, " ")
        For c = 1 To Len(word)
          char = Mid(word, c, 1)
          ForEach characters()
            If characters()\id = Asc(char)
              wordWidth + characters()\w
              Break
            EndIf
          Next
        Next
        If lineWidth + wordWidth > maxWidth
          AddElement(lines())
          lines() = currentLine
          currentLine = word
          lineWidth = wordWidth + spaceWidth
        Else
          If currentLine <> ""
            currentLine + " "
          EndIf
          currentLine + word
          lineWidth + wordWidth + spaceWidth
        EndIf
      Next
      AddElement(lines())
      lines() = currentLine
  EndSelect
EndProcedure

NewList lines.s()
SplitText("HELLO WORLD", #TEXT_WRAP_WORD, 64, lines())
ForEach lines()
  Debug lines()
Next
FreeList(lines())
Little John
Addict
Addict
Posts: 4805
Joined: Thu Jun 07, 2007 3:25 pm
Location: Berlin, Germany

Re: Word wrapping

Post by Little John »

These are my word wrap functions.
Post Reply