0

I am trying to create a 'jeopardy' type game and i have gotten to the point where you just have to click on a box and a question box will appear.

Im using a customPictureBox, essentially overriding text and such:

  protected override void OnPaint(PaintEventArgs pe)
    {
        base.OnPaint(pe);
        Size size = TextRenderer.MeasureText(text, font);
        int x = Width / 2 - size.Width / 2;
        int y = Height / 2 - size.Height / 2;
        pe.Graphics.DrawString(text, font, new SolidBrush(color), x, y);
    }

on the game i add its properties like this:

  CustomPictureBox box = new CustomPictureBox()
        {
            Text = ((QuestionBox)sender).Question.Text.ToUpper(),
            SizeMode = PictureBoxSizeMode.StretchImage,
            Font = new Font("Comic Sans MS", 40),
            Image = Properties.Resources.MainTile,
            ForeColor = Color.White,
            BorderStyle = BorderStyle.FixedSingle,
            Dock = DockStyle.Fill
        };

The problem comes when the text length exceeds certain amount of (depending on the monitor) words, essentially what happens is that the text is drawn but a majority of it goes outside of the form, adding Autosize and Maximum size Reference, this adds the MaxSize to the whole CustomPictureBox.

This solution seems to put an offset for the words, making longer sentences fly completely off the screen.

Ideally I need to add a newline til the words reach a preset boundary so they wouldn't go off the form.

Flame
  • 35
  • 4

1 Answers1

0

Do not use Graphics.DrawString, use TextRenderer.DrawText instead.
Specifically, use this overload since it accepts
IDeviceContext - that's your Graphics instance, 
String - that's the string to draw,
Font - that's the font to use, 
Rectangle - that's the rectangle to use for boundaries, 
Color - that's the fore color to use, 
And TextFormatFlags - that's a flags enum that allows you to specify how to wrap text - using either default or WordBreak.

So, replace this row:

pe.Graphics.DrawString(text, font, new SolidBrush(color), x, y);

With this:

var flags = TextFormatFlags.HorizontalCenter | 
            TextFormatFlags.VerticalCenter | 
            TextFormatFlags.WordBreak;
TextRenderer.DrawText(pe.Graphics, text, font, pe.ClipRectangle, ForeColor, flags);
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • Indeed it does work but is there a way to manipulate this more? Since at a point it seems to cut off the rest of the text, though yes at that point its not common to have such a long of a question.. – Flame Nov 23 '17 at 18:39
  • You can start at the top left corner instead of horizontal and vertical center, you can add ellipsis (...) where the text doesn't fit the control, or you can play with the font size or the control size. Other then that, I don't think there is much you can do. You can't paint the text outside the control's boundaries like Excel does if the text is too long for a cell. – Zohar Peled Nov 23 '17 at 18:42