gpt4 book ai didi

c# - 覆盖标签 OnPaint?

转载 作者:行者123 更新时间:2023-11-30 20:06:29 25 4
gpt4 key购买 nike

我正在尝试使用 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);
}
}

当我运行它时,标签的文本是一样的,它没有使用 FillPath 绘制。

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

谢谢。

刚试过:

e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
e.Graphics.FillPath(br, path);

没用。

最佳答案

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

我不确定您尝试使用 GraphicsPath 实现什么。也许您可以改用 TextRenderer

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

更新:

我将表单切换为 Aero Glass 并进行了一些测试。使用 TextRenderer 和使用 GraphicsPath 的两种方法都有效,但是 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();

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

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);
}

自定义 Label 必须有黑色背景。黑色部分将显示为玻璃。它的最小尺寸必须约为 (125, 70) 才能适合您的文本,因为您从 (55, 55) 开始绘制。 (您的标签是否太小?)您必须将 AutoSize 更改为 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);
}

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


我在 this article of TheCodeKing 中找到了玻璃效果的代码.

关于c# - 覆盖标签 OnPaint?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9692524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com