修改 TextBox 控件中的字符间距/宽度

Ale*_*lex 3 .net fonts textbox richtextbox winforms

我正在尝试动态设置 TextBox 控件中每个字符的间距(宽度)。我已经做了大量的阅读,我认为这在普通的 TextBox 中是不可能的。我对 RichTextBox 或任何其他可以解决此问题的控件持开放态度。

为了证明这是可能的,我打开了 Word,我能够选择一个字符并调整其间距并将其“拉伸”出来。我希望在我的 .NET 应用程序中实现相同的行为。

修改 M

是否有代码示例或控件显示如何实现?

Sim*_*ier 5

如果您接受链接到某些 WPF 的程序集(WindowsBase 和 PresentationCore),则可以编写自定义 TextBox 并在 WinForms 实现中使用它。WPF 有一些不错的类,如GlyphTypeFace(允许加载字体文件并从字形构建几何图形)和GlyphRun(它允许绘制字形列表 - 文本)。但是我们这里不能使用 GlyphRun,因为我们希望能够修改一些字形的几何形状。所以我们需要手动获取几何图形并对其进行转换。

下面是一个例子:

Winforms 代码:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // ElementHost allows Winforms to host WPF visual components
        ElementHost host = new ElementHost();
        host.Dock = DockStyle.Fill;
        host.Child = new MyTextBox();
        Controls.Add(host);
    }
Run Code Online (Sandbox Code Playgroud)

自定义文本框代码:

public class MyTextBox: UIElement
{
    protected override void OnRender(DrawingContext drawingContext)
    {
        const string sampleText = "Sample String";
        const int sampleEmSize = 30;

        GlyphTypeface typeFace = new GlyphTypeface(new Uri("file:///C:/WINDOWS/FONTS/segoeui.ttf"));

        GeometryGroup group = new GeometryGroup();
        group.FillRule = FillRule.Nonzero;

        double x = 0;
        double y = sampleEmSize;
        for (int i = 0; i < sampleText.Length; i++)
        {
            ushort glyphIndex = typeFace.CharacterToGlyphMap[sampleText[i]];
            Geometry glyphGeometry = typeFace.GetGlyphOutline(glyphIndex, sampleEmSize, sampleEmSize).Clone();
            TransformGroup glyphTransform = new TransformGroup();

            if (sampleText[i] == 'm') // this is a sample, we just change the 'm' characte
            {
                const double factor = 2;
                glyphTransform.Children.Add(new ScaleTransform(factor, 1));
                glyphTransform.Children.Add(new TranslateTransform(x, y));
                x += factor * typeFace.AdvanceWidths[glyphIndex] * sampleEmSize;
            }
            else
            {
                glyphTransform.Children.Add(new TranslateTransform(x, y));
                x += typeFace.AdvanceWidths[glyphIndex] * sampleEmSize;
            }

            glyphGeometry.Transform = glyphTransform;
            group.Children.Add(glyphGeometry);
        }

        drawingContext.DrawGeometry(Brushes.Black, null, group);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是 WinForms 上的结果:

在此处输入图片说明

当然,如果你想支持编辑,还有一些工作要做,但这可能会让你开始。