How do I fix the alpha value after calling GDI text functions?

谁说胖子不能爱 提交于 2019-12-06 08:12:23

Below is the solution I eventually came up with. It's kind of ugly and could probably be simplified, but it works. The idea is to create a BufferedGraphics object based on the original Graphics object (i.e., the screen). In the BufferedGraphics object, TextRenderer.DrawText() will render the text exactly like it would if it was drawing to the screen. I then create a regular graphics object, copy the Buffered Graphics object to the regular graphics object, and finally draw the regular graphics object to the screen.

Rectangle inner = new Rectangle(Point.Empty, ContentRectangle.Size);
using (BufferedGraphics bg = BufferedGraphicsManager.Current.Allocate(e.Graphics, inner)) {
    using (Bitmap bmp = new Bitmap(inner.Width, inner.Height, bg.Graphics)) {
        using (Graphics bmpg = Graphics.FromImage(bmp)) {
            bg.Graphics.Clear(BackColor);
            do_my_drawing(bg.Graphics);
            bg.Graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
            e.Graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
            bmpg.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;

            bg.Render(bmpg);
            e.Graphics.DrawImageUnscaledAndClipped(bmp, ContentRectangle);
        }
    }
}

Setting all of the CompositingMode attributes probably isn't necessary, but once I got it working I didn't bother testing all the permutations to figure out which, if any, are needed.

You might want to try using GDI+ on a separate bitmap, copying that to the screen. The advantage is that the alpha of text drawn with GDI+ will show the color of the bitmap (which you would've painted white) instead of making the bitmap transparant.

But indeed, GDI+ has very buggy or just inaccurate text measuring functionality. But maybe you can use the GDI functions for that. In the end, your GDI+ text rendering should look exactly like the GDI text rendering you have now, so it might be worth a try.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!