none
Setting Line-spacing / Font stretch RRS feed

  • Question

  • Hi,

    I'm using the ..NET 2.0 Framework and I am trying to draw a string onto my control with a pre-defined line spacing. I looked at the TextRenderer.DrawText() and Graphics.DrawString() functions but they do not provide this functionality. Does anyone know how I can achieve this without having to render each character independently?

    Thanks for your tips!

    Regards,

    Mark
    Monday, April 23, 2007 10:09 AM

Answers

  • Try something like this:

        private void Form1_Paint(object sender, PaintEventArgs e) {
          e.Graphics.DrawRectangle(Pens.Black, new Rectangle(0, 0, 100, 500));
          string txt = "A long line we're trying to fit inside a rectangle with custom line spacing";
          SizeF fit = new SizeF(100, this.Font.Height);
          StringFormat fmt = StringFormat.GenericTypographic;
          int spacing = (int)(1.5 * this.Font.Height);
          int line = 0;
          for (int ix = 0; ix < txt.Length; ) {
            int chars, lines;
            e.Graphics.MeasureString(txt.Substring(ix), this.Font, fit, fmt, out chars, out lines);
            e.Graphics.DrawString(txt.Substring(ix, chars), this.Font, Brushes.Black, 0, spacing * line);
            ++line;
            ix += chars;
          }
        }

    Monday, April 23, 2007 3:31 PM
    Moderator

All replies

  • Try something like this:

        private void Form1_Paint(object sender, PaintEventArgs e) {
          e.Graphics.DrawRectangle(Pens.Black, new Rectangle(0, 0, 100, 500));
          string txt = "A long line we're trying to fit inside a rectangle with custom line spacing";
          SizeF fit = new SizeF(100, this.Font.Height);
          StringFormat fmt = StringFormat.GenericTypographic;
          int spacing = (int)(1.5 * this.Font.Height);
          int line = 0;
          for (int ix = 0; ix < txt.Length; ) {
            int chars, lines;
            e.Graphics.MeasureString(txt.Substring(ix), this.Font, fit, fmt, out chars, out lines);
            e.Graphics.DrawString(txt.Substring(ix, chars), this.Font, Brushes.Black, 0, spacing * line);
            ++line;
            ix += chars;
          }
        }

    Monday, April 23, 2007 3:31 PM
    Moderator
  • Your code is work only for font.Size small than 9. If font size is big than 8 then cycle are loopied because variable CHARS set to 0.  Do it normal for any size of font, dude.
    • Edited by prmchnk Thursday, April 4, 2013 7:16 AM
    Thursday, April 4, 2013 7:11 AM