Setting label height to fit number of lines in label text

Hi

I am trying to make a label height fit the number of lines the label text has. I want the font size to be relative to the height of the component that holds the label. This is how I do it:

            int fontSize = getHeight() / 16;

            String s = label->getText();

            int numberOfNewlineChars = 0;

            CharPointer_UTF8 pChar = s.getCharPointer();

            for (int i=0;i<s.length();i++)

            {

                if (*pChar++ == '\n')

                {

                    numberOfNewlineChars++;

                }

            }

            int b = label->getHorizontalBorderSize ();

            int labelHeight = numberOfNewlineChars*((b*2) + fontSize);

            label->setFont(fontSize);

            label->setBounds(0, 0, getWidth(), labelHeight);

 

The label height does not fit the number of lines, what I see is that in the iPad simulator the height is to little to fit the text and in the iPhone 4 inch retina simulator there is to much empty space left after the text. Any ideas on what I am missing here is very welcome or suggestions on how to do this in other ways. Thanks.

best regards

John

 

Haven't tried this specifically myself but have you taken a look at the TextEditor class?  It has a getTextHeight method and can be set to readonly so it's quite label-like.  The only thing is that the TextEditor doesn't support justification so if you need that then it wouldn't work.

Hi Graeme

Thank you for your input. I found out what was wrong. I found out that the issue was some lines of text that did not fit within the width of the label, and hence they where split into more lines. This meant that there was actually more lines of text than my newline count told me. I have fixed it by taking adjusting the line length too. Your idea is a good alternative, but I do need to set the justification though. Thanks.

Best regards

John