gpt4 book ai didi

c# - c#中重载控件绘制有文本渲染问题

转载 作者:太空宇宙 更新时间:2023-11-03 14:57:14 24 4
gpt4 key购买 nike

我已经对控件 (ToolStripStatusLabel) 进行了子类化,以尝试覆盖它的绘制方式。目前我希望这段代码实际上什么都不做,但它会导致一个奇怪的输出:

protected override void OnPaint(PaintEventArgs e)
{
// Create a temp image to draw to and then put that onto the control transparently
using (Bitmap bmp = new Bitmap(this.Width, this.Height))
{
using (Graphics newGraphics = Graphics.FromImage(bmp))
{
// Paint the control to the temp graphics
PaintEventArgs newEvent = new PaintEventArgs(newGraphics, e.ClipRectangle);
base.OnPaint(newEvent);

// Copy the temp image to the control
e.Graphics.Clear(this.BackColor);
e.Graphics.DrawImage(bmp, new Rectangle(0, 0, this.Width, this.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel);//, imgAttr);
}
}
}

当我运行这段代码时,控件上的文本非常奇怪,预期的图像在顶部,实际输出在底部:

output

看起来当控件绘制文本时,alpha 与抗锯齿文本的混合出错了。

我尝试过的事情:

  • 设置e.graphicsnewGraphics的合成模式
  • 设置 TextRenderingHint
  • newGraphics 的像素格式设置为 32Bpp ARGB 和 Premultiplied ARGB
  • 在要求基类呈现之前用控件背景颜色清除 newGraphics

最佳答案

TL;DR:您需要自己使用 custom renderer 呈现文本重新实现 OnRenderItemText,最终可能使用 graphics.DrawString() 进行绘图。

另一种选择是使用 label in the status bar (正如@Reza Aghaei 所提到的)。然后您可以将 UseCompatibleTextRendering 设置为 true 以使其使用 GDI+ 而不是 GDI


这似乎是文本在最低级别呈现方式的固有问题。如果您添加一个普通的 ToolStripStatusLabel 并将其 TextDirection 设置为 Vertical90,那么您会得到相同的结果,其中文本的抗锯齿似乎没有背景的 alpha。

查看 source您会看到在将文本呈现为位图然后在本例中进行旋转的地方调用了一段非常相似的代码:

            using (Bitmap textBmp = new Bitmap(textSize.Width, textSize.Height,PixelFormat.Format32bppPArgb)) {

using (Graphics textGraphics = Graphics.FromImage(textBmp)) {
// now draw the text..
textGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
TextRenderer.DrawText(textGraphics, text, textFont, new Rectangle(Point.Empty, textSize), textColor, textFormat);
textBmp.RotateFlip((e.TextDirection == ToolStripTextDirection.Vertical90) ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone);
g.DrawImage(textBmp, textRect);
}
}

因此,当文本呈现给位图图形上下文(与控件的图形上下文相对)时,这似乎是一个基本问题。最终code that is called是:

        using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, flags ))
{
using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont( font, fontQuality )) {
wgr.WindowsGraphics.DrawText( text, wf, bounds, foreColor, GetIntTextFormatFlags( flags ) );
}
}

我认为它正在涉足具有 trouble with alpha on text 的 GDI(而不是 GDI+) .

最好的办法是写一个 custom renderer重新实现 OnRenderItemText,可能从 default implementation 的源代码中获得了一些“灵感” .

关于c# - c#中重载控件绘制有文本渲染问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405796/

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