覆盖标签OnPaint?

Tan*_*r.R 2 c# label system.drawing custom-controls

我正在尝试使用FillPath覆盖我自己的自定义控件中的标签的OnPaint方法.

这是我的控件代码:

public partial class GlassLabel : Label
{
    public GlassLabel()
    {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        Graphics g = this.CreateGraphics();
        GraphicsPath path = new GraphicsPath();
        SolidBrush br = new SolidBrush(Color.Black);
        path.AddString("LLOOOOLL", new FontFamily("Microsoft Sans Serif"), (int)FontStyle.Regular, 12, new Point(55, 55), StringFormat.GenericDefault);
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.FillPath(br, path);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,标签的文本是相同的,它不会使用FillPath绘制.

我试图覆盖标签的原因是我想在Aero玻璃上使用它,这需要FillPath.如果我可以将图形(FillPath)转换为对象以便我可以将事件附加到它,我也想了解相关信息.

谢谢.

刚试过:

e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
        e.Graphics.FillPath(br, path);
Run Code Online (Sandbox Code Playgroud)

没工作.

Oli*_*bes 7

不要创建新的Graphics对象,而是使用参数中e.Graphics提供的对象PaintEventArgs.

我不确定你想要实现的目标GraphicsPath.也许你可以TextRenderer改用它.

protected override void OnPaint(PaintEventArgs e)
{
    TextRenderer.DrawText(e.Graphics, "LLOOOOLL", Font, ClientRectangle, ForeColor, 
        TextFormatFlags.Left | TextFormatFlags.VerticalCenter); 
}
Run Code Online (Sandbox Code Playgroud)

更新:

我将表格切换到Aero Glass并进行了一些测试.两种方法都带有TextRendererGraphicsPath有效,但TextRenderer由于ClearType在玻璃上产生伪像,因此效果不佳.

这些API声明是必需的

[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
    public int Left;
    public int Right;
    public int Top;
    public int Bottom;
}

[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern void DwmExtendFrameIntoClientArea (IntPtr hwnd, 
                                                        ref MARGINS margins);

[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern bool DwmIsCompositionEnabled();
Run Code Online (Sandbox Code Playgroud)

在表单的构造函数中,我有这个代码

InitializeComponent();

if (DwmIsCompositionEnabled()) {
    // Stretch the margins into the form for the glass effect.
    MARGINS margins = new MARGINS();
    margins.Top = 300;
    DwmExtendFrameIntoClientArea(this.Handle, ref margins);
}
Run Code Online (Sandbox Code Playgroud)

自定义Label必须具有黑色背景.黑色部分将显示为玻璃.它必须具有大约(125,70)的最小尺寸才能适合您的文本,因为您开始绘制(55,55).(您的标签是否太小?)您必须更改AutoSizeto false才能更改标签的大小.这是自定义标签的代码

protected override void OnPaint(PaintEventArgs e)
{
    GraphicsPath path = new GraphicsPath();
    SolidBrush br = new SolidBrush(Color.FromArgb(1, 0, 0));
    path.AddString("LLOOOOLL", Font.FontFamily, (int)Font.Style, Font.SizeInPoints, 
                   new Point(55, 55), StringFormat.GenericDefault);
    e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
    e.Graphics.FillPath(br, path);
}
Run Code Online (Sandbox Code Playgroud)

有一些差异,它与您的代码相同.一个重要的区别是文字颜色必须与黑色不同; 否则,它会显示为玻璃.我只是采用实际标签字体的字体属性.这样,您可以在属性窗口中更改其外观.


我在TheCodeKing的这篇文章中找到了玻璃效果的代码.