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

在C# .NET Core 6 WinForm中如何设置字体粗细?

问题描述

我用C# .NET Core 6 + WinForm开发一款图片拼接与文字添加工具,目标是实现Photoshop中Diablo Light字体的输出效果(标题“Baldur the invincible”的展示效果如下):
Photoshop目标效果

但实际用DrawString配合Font("Diablo", 30, FontStyle.Regular)输出的效果偏粗:
我的Regular输出效果

系统字体列表里只能看到Diablo Regular,尝试用FontStyle.Bold后效果更粗,完全无法匹配Photoshop的Light字体效果:
我的Bold输出效果

相关代码片段:

// 文本处理逻辑
{
    Font title_font = new Font("Diablo", 30, FontStyle.Regular);
    Font sub_font = new Font("Diablo", 25, FontStyle.Regular);
    List<Font> list_fonts = new List<Font>();
    list_fonts.Add(title_font);
    list_fonts.Add(sub_font);

    RectangleF tit_rect = new RectangleF(165, 70, w - (165 * 2), h);
    var v = m_dict_titles["Title"];
    string curr_string = tabbed_value[v].ToUpper();
    float offsety = WriteTitleTextf2(map_back, 0, TL(curr_string, false), tit_rect, list_fonts, StringAlignment.Near, 5);
}

public void WriteOnBitmapf(Bitmap bmp, int col, Font font, String text, RectangleF rectf, StringAlignment st_align, float stringi = 0.0f)
{
    float size = font.Size;
    Graphics g = Graphics.FromImage(bmp);
    g.SmoothingMode = SmoothingMode.AntiAlias;
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
    g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

    StringFormat format = new StringFormat()
    {
        Alignment = st_align,
        LineAlignment = StringAlignment.Near
    };

    Brush br = col == 0 ? new SolidBrush(Color.FromArgb(0, 0, 0)) : new SolidBrush(Color.FromArgb(255, 255, 255));
    g.DrawString(text, font, br, rectf, format);
    g.Flush();
}
解决方法

1. 直接指定字体完整名称

多数字体的Light版本是独立的字体家族,尝试直接用“Diablo Light”作为字体名创建Font:

Font title_font = new Font("Diablo Light", 30, FontStyle.Regular);

只要系统中正确安装了该字体,就能直接调用到Light版本。

2. 通过FontWeight指定细体

如果“Diablo”字体家族包含Light权重,可使用带FontWeight参数的Font构造函数(.NET Core 3.0+支持):

Font title_font = new Font(
    new FontFamily("Diablo"),
    30,
    FontStyle.Regular,
    GraphicsUnit.Point,
    1,
    false,
    FontWeight.Light
);

FontWeight枚举提供Light、ExtraLight等选项,可对应不同细体等级。

3. 用PrivateFontCollection加载本地字体文件

若系统字体识别异常,直接从本地.ttf/.otf文件加载Diablo Light版本:

using System.Drawing.Text;

// 初始化私有字体集合
PrivateFontCollection privateFonts = new PrivateFontCollection();
// 加载本地Diablo Light字体文件
privateFonts.AddFontFile(@"C:\你的字体路径\Diablo-Light.ttf");

// 创建字体实例
Font title_font = new Font(privateFonts.Families[0], 30, FontStyle.Regular);

这种方式不受系统字体列表限制,能确保调用到指定的字体版本。

4. 检查字体安装状态

打开系统字体设置,确认Diablo Light字体是否已正确安装。部分场景下Photoshop会自带字体但未安装到系统,导致.NET无法识别,手动安装后即可正常调用。


内容的提问来源于stack exchange,提问作者Renato Tarabella

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:25:18