Centering text on a display?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nigelmercier
    New Member
    • Dec 2009
    • 45

    Centering text on a display?

    Now I've got a result for my text formatting problem [clicky] thanks to weaknessforcats , my next task is to centre the text on the display.

    This isn't a normal display, it is a small LCD with custom drivers that I have written. I can manipulate where the cursor is, but first I need to calculate the horizontal offset based on the number (0 - 9999) that I want to display.

    My first thought was a series of if statements that checked the number (say n)for n>9, n>99, or n>999 then set the offset accordingly. It would work, but not very elegant.

    Any thoughts?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Write a function that takes your string and a field width.

    Use strlen to get the string length. Subtract that length from the field width, divide by 2. Display that number of spaces and then the string.

    If the string is larger than the field width, display **** or ##### to signal the field is too small.

    Comment

    • nigelmercier
      New Member
      • Dec 2009
      • 45

      #3
      Does strlen ignore leading spaces then?

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        It does not.

        If you have leading spaces you would do the same calculation to get the offset. Then count the leading spaces. Divide that count by 2 and add the quotient to your offset.

        Then display the string starting that the first non-space character.

        You will have the address of that first non-space character from the loop you used to count the number of leadin spaces.

        Comment

        Working...