C#文本框行间距

3

我正在开发一个 Paint.net 插件,用于将当前图像转换为 ASCII 艺术。我已经成功完成了转换,并将 ASCII 艺术输出到一个 TextBox 控件中,使用等宽字体。然而,由于 TextBox 中的行间距,ASCII 艺术在纵向上被拉伸了。有没有办法设置 TextBox 的行间距?


1
也许可以使用 RichTextBox 并设置行高:http://social.msdn.microsoft.com/forums/en-US/vblanguage/thread/8781caf6-5759-4fee-8c08-cd8a2d85fc9f? - Ranhiru Jude Cooray
2个回答

4
一个文本框只显示单行或多行文本,没有格式选项。它可以有字体,但是这只适用于文本框而不是文本,所以据我所知,您不能设置段落设置,如行间距。

我的第一个建议是使用RichTextBox,但是再次提醒,RTF没有行间距的代码,因此我认为这也是不可能的。

因此,我的最终建议是使用自绘控件。对于固定宽度字体,这应该不太困难——您知道每个字符的位置是(x*w, y*h),其中xy是字符索引,wh是一个字符的大小。

编辑:再仔细考虑一下,它甚至更简单——只需将字符串分成几行并绘制每一行即可。


这是一个简单的控件,就是这样做的。在测试时,我发现对于Font = new Font(FontFamily.GenericMonospace, 10, FontStyle.Regular)Spacing的最佳值为-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
你可以通过编程方式来设置属性,通过Block class
TextBox tbox = new TextBox();
tbox.SetValue(Block.LineHeightProperty, 10.0);

或者,如果你想在Xaml中完成这个任务:
<TextBox Block.LineHeight="10" /> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接