我正在开发一个 Paint.net
插件,用于将当前图像转换为 ASCII 艺术。我已经成功完成了转换,并将 ASCII 艺术输出到一个 TextBox
控件中,使用等宽字体。然而,由于 TextBox
中的行间距,ASCII 艺术在纵向上被拉伸了。有没有办法设置 TextBox
的行间距?
我正在开发一个 Paint.net
插件,用于将当前图像转换为 ASCII 艺术。我已经成功完成了转换,并将 ASCII 艺术输出到一个 TextBox
控件中,使用等宽字体。然而,由于 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; }
}
TextBox tbox = new TextBox();
tbox.SetValue(Block.LineHeightProperty, 10.0);
<TextBox Block.LineHeight="10" />