You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C#的GraphicsPath消除文本单词间的多余间距?

解决GraphicsPath绘制波斯语文本时的多余间距问题

问题原因

波斯语属于从右到左(RTL)的书写系统,默认的StringFormat未适配RTL文本排版规则,导致字符间距计算异常;同时原代码中先创建文本路径再执行缩放变换,会进一步放大原本不合理的间距。

修复后的代码

Bitmap btm = new Bitmap(800, 400);
using (Graphics g = Graphics.FromImage(btm))
using (GraphicsPath gp = new GraphicsPath())
using (Pen outline = new Pen(Brushes.Green, 2) { LineJoin = LineJoin.Round })
using (StringFormat sf = new StringFormat())
using (Brush foreBrush = new SolidBrush(System.Drawing.Color.White))
using (Font font = new Font("Lalezar", 26, FontStyle.Regular))
{
    // 适配RTL文本排版
    sf.FormatFlags = StringFormatFlags.DirectionRightToLeft;
    sf.Alignment = StringAlignment.Near;
    sf.LineAlignment = StringAlignment.Near;

    // 先设置缩放变换,再创建文本路径
    g.ScaleTransform(8f, 8f);
    g.SmoothingMode = SmoothingMode.AntiAlias;
    g.InterpolationMode = InterpolationMode.Bilinear;
    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
    g.CompositingQuality = CompositingQuality.HighQuality;

    // 在缩放后的坐标系中添加文本路径
    gp.AddString("سلام", font.FontFamily, (int)font.Style, font.Size, new PointF(0, 0), sf);
    
    g.DrawPath(outline, gp);
    g.FillPath(foreBrush, gp);
}

关键调整点

  • RTL文本适配:为StringFormat添加DirectionRightToLeft标志,让GDI+按照波斯语的书写方向计算字符间距。
  • 变换顺序优化:将ScaleTransform移到创建文本路径之前,确保文本路径是在缩放后的坐标系中生成,避免路径被二次放大导致间距失真。
  • 资源管理优化:显式创建Font对象并纳入using块,确保资源正确释放。

内容的提问来源于stack exchange,提问作者ماهان نوروزی

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 22:12:25