Page 1 of 1

Word wrapping

Posted: Tue Mar 05, 2024 7:59 pm
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())

Re: Word wrapping

Posted: Wed Mar 06, 2024 11:49 am
by Little John
These are my word wrap functions.