c# - 在 C# 中设置带有轮廓颜色的字体

标签 c# winforms fonts label outline

我在我的代码中向面板动态添加标签。

我想做的是能够勾勒出字体的轮廓,以便它可以从面板的背景颜色中脱颖而出。

问题是我不知道如何使用 Winforms 在 C# 中为我的字体创建轮廓甚至阴影效果。

任何人都知道我应该看什么或可以指出正确的方向吗? 如果你不明白我的意思,下图就是我想要的:(外衬)

enter image description here

最佳答案

我认为您必须自定义绘制自己的控件。下面是一个 Label 的例子。请注意,这只是一个演示,您应该尝试在 winforms 中找到更多关于自定义绘画的信息:

public class CustomLabel : Label
{
    public CustomLabel()
    {
        OutlineForeColor = Color.Green;
        OutlineWidth = 2;
    }
    public Color OutlineForeColor { get; set; }
    public float OutlineWidth { get; set; }
    protected override void OnPaint(PaintEventArgs e)
    {
        e.Graphics.FillRectangle(new SolidBrush(BackColor), ClientRectangle);
        using (GraphicsPath gp = new GraphicsPath())
        using (Pen outline = new Pen(OutlineForeColor, OutlineWidth)
            { LineJoin = LineJoin.Round})
        using(StringFormat sf = new StringFormat())
        using(Brush foreBrush = new SolidBrush(ForeColor))
        {
            gp.AddString(Text, Font.FontFamily, (int)Font.Style,
                Font.Size, ClientRectangle, sf);                                
            e.Graphics.ScaleTransform(1.3f, 1.35f);
            e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
            e.Graphics.DrawPath(outline, gp);                
            e.Graphics.FillPath(foreBrush, gp);                            
        }
    }
}

您可以通过OutlineForeColor 属性更改轮廓颜色,您可以通过OutlineWidth 属性更改轮廓宽度。当您在设计器中更改这些属性时,效果不会立即应用(因为没有任何代码可以做到这一点,我想保持简短),效果仅在表单获得焦点时应用。

您可以添加更多的是将 TextAlign 映射到 StringFormatAlignment(在中命名为 sf代码),您还可以覆盖一些事件引发方法以增加对外观的更多控制(例如当鼠标悬停在标签上时更改 ForeColor ...)。您甚至可以创建一些阴影效果和发光效果(这需要更多代码)。

enter image description here

关于c# - 在 C# 中设置带有轮廓颜色的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19842722/

相关文章:

c# - 如何在更新后不断刷新datagridview

c# - 如何制作类似聊天的界面/显示?

css - 使用webpack加载字体: font decode issue

c# - 有没有一种简短的方法来替换 C# 中字符串中的两个字符?

c# - 将事件处理程序附加到 mshtml.DispHTMLInputElement

c# - 这是对设置功能的滥用吗?

css - 从 gulp iconfontCss 到 Webpack

css - 所有字体都会在浏览器上占据相同的空间并具有相同的值吗?

c# - ASP.NET WebAPI Ajax 取得进展

c# - System.Byte[*] 是什么类型