Search code examples
c#tooltipmonogame

Rectangle's width increasing more than it should while trying to resize the rectangle


I don't think the title is on the spot. But please check the pictures below for a better demonstration.

I have a rectangle which fits text in it. What I'm trying to do is that, if the rectangle's height is bigger than the screen, then the rectangle should resize.

Resizing goes as follows: set the height to screen height, increase width, try to fit text, repeat.

Here is the method that parses my text, it returns the string that would fit in the rectangle given the width.

private String parseText(String text, int Width)
{
    String line = String.Empty;
    String returnString = String.Empty;
    String[] wordArray = text.Split(' ');
    int i = 1;
    foreach (String word in wordArray)
    {
        if (Font.MeasureString(line + word).Length() > Width)
        {
            returnString = returnString + line + '\n';
            line = String.Empty;
            i++;
        }

        line = line + word + ' ';
    }
    this.Size = new Size(Size.Width, (int)Font.MeasureString(returnString + line).Y);
    return returnString + line;
}

This part works really well. However, if the text exceeds the height, the text is drawn outside of the rectangle. So I added this:

public string Text
{
    get { return text; }
    set
    {
        temp = parseText(value.Replace("\n", ""), Size.Width);
        while(Size.Height > Viewport.Height)
        {
            Size = new Size(Size.Width + 5, Viewport.Height);
            temp = parseText(value, Size.Width);
        }
        text = temp;
    }
}

This is my problem:

Part 1: Text is ok. Does not hit the screen's edge

Part 2: Right after hitting the screen edge by adding a bunch of 'hello'

Part 3: Adding one more "hello" properly fixes the issue.

What is happening in Part 2? How does it get resized like that? Why is it fixed in part 3?

Note: Regardless of what I add here: Size = new Size(Size.Width + 5, Viewport.Height); either +5, or 5% of the screen, or 20% or 200% it still gets resized to the same amount.

Comment for more information. Thanks


Solution

  • Fixed by adding: value.Replace("\n", "") in temp = parseText(value, Size.Width);

    I was doing that before the while loop, but not inside it. Therefore, the text was getting a bunch of new lines, and when it got called again, the new lines disappeared before the while loop.

    It should look like this: temp = parseText(value.Replace("\n", ""), Size.Width - (int)LeftMargin);