Paint.net
插件,将当前图像转换为 ASCII 艺术。我的转换工作正常,它将 ASCII 艺术输出到 TextBox
控件中,并具有固定宽度的字体。我的问题是,由于文本框中的行距,ASCII 艺术被垂直拉伸。有没有办法设置TextBox
的行间距?
文本框仅显示单行或多行文本,没有格式选项 - 它可以有一种字体,但适用于文本框而不是文本,因此据我所知,您不能进行行间距等段落设置。
我的第一个建议是使用 RichTextBox,但话又说回来,RTF 没有行距代码,所以我相信这也是不可能的。
所以我最终的建议是使用所有者绘制的控件。使用固定宽度的字体应该不会太困难 - 你知道每个字符的位置是
(x*w, y*h)
,其中 x
和 y
是字符索引,w
和 h
是一个字符的大小性格。
编辑:再想一想,它甚至更简单 - 只需将字符串分成几行并绘制每条线即可。
这是一个简单的控件,可以实现此目的。测试时我发现对于
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; }
}
您可以通过 Block 类设置属性以编程方式执行此操作:
TextBox tbox = new TextBox();
tbox.SetValue(Block.LineHeightProperty, 10.0);
或者,如果您想在 Xaml 中执行此操作:
<TextBox Block.LineHeight="10" />