开发者

C# TextBox Line Spacing

I'm working on a plugin for Paint.net that converts the current image to ASCII art. I have the conversion working fine, and it outputs the ASCII art into a TextBox control, with a fixed开发者_如何学Go width font. My problem is, the ASCII art is stretched vertically, because of the line spacing in a TextBox. Is there any way to set the line spacing of a TextBox?


A TextBox simply shows single or multiline text with no formatting options - it can have a font but that applies to the TextBox and not to the text, so you can't have paragraph settings like line spacing as far as I know.

My first suggestion would be to use a RichTextBox, but then again, RTF doesn't have a code for line spacing so I believe that would be impossible as well.

So my final suggestions is to use an owner-drawn control. It shouldn't be too difficult with a fixed-width font - you know the location of each character is (x*w, y*h) where x and y are the character index and w and h are the size of one character.

Edit: Thinking about it a bit more, it's even simpler - simply separate the string to lines and draw each line.


Here's a simple control that does just that. When testing it I found that for Font = new Font(FontFamily.GenericMonospace, 10, FontStyle.Regular), the best value for Spacing was -9.

/// <summary>
/// Displays text allowing you to control the line spacing
/// </summary>
public class SpacedLabel : Control {
    private string[] parts;

    protected override void OnPaint(PaintEventArgs e) {
        Graphics g = e.Graphics;
        g.Clear(BackColor);

        float lineHeight = g.MeasureString("X", Font).Height;

        lineHeight += Spacing;

        using (Brush brush = new SolidBrush(ForeColor)) {
            for (int i = 0; i < parts.Length; i++) {
                g.DrawString(parts[i], Font, brush, 0, i * lineHeight);
            }
        }
    }

    public override string Text {
        get {
            return base.Text;
        }
        set {
            base.Text = value;
            parts = (value ?? "").Replace("\r", "").Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
        }
    }

    /// <summary>
    /// Controls the change in spacing between lines.
    /// </summary>
    public float Spacing { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜