About the solution of black ghosting on the edge when GDI+ draws on a transparent Bitmap (in WPF)

Recently, I was doing the homework of the software engineering course. In one place, I needed to use GDI+ to draw an image and pass the handle to the tray as a tray icon. However, because the landlord himself has serious obsessive-compulsive disorder, he found some small problems during the test:

 The red line is the icon on the far left of the tray area    

When the bottom is dark, there is no difference between "41" and "38" on the right, but when the bottom is white, you can see that the icon at the "41" position is very black. Why?


It should be processed with GDI+ for layer compounding, just like in JAVA Swing before, where there is transparency (that is, semi-transparency), its color will be processed by GDI+ to be mixed with black when it is output to the image. Therefore, by default, the font will have a Cleartype effect, smoothing the edge, that is, diffusing the pixels on the edge and filling the surrounding with some transparent pixels. In this way, the above situation will occur when this bufferedimage is exported to other formats with transparency

To avoid this just draw with the last configuration:

g.SmoothingMode = SmoothingMode.HighSpeed;
            g.CompositingQuality = CompositingQuality.HighSpeed;
            g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;

The whole process is as follows:

        private Icon GetImageSourceByText(String Inf)
        {
            Drawing.Image bufferedimage;
            if (ico == IntPtr.Zero)
                bufferedimage = new Bitmap(35, 30, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            else
                bufferedimage = Bitmap.FromHicon(ico);

            Graphics g = Graphics.FromImage(bufferedimage);
            g.Clear(Color.FromArgb(0, 255, 255, 255));
            g.SmoothingMode = SmoothingMode.HighSpeed;
            g.CompositingQuality = CompositingQuality.HighSpeed;
            g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
            Pen pen = new Pen(Color.FromArgb(255, 255, 255, 255), 2);
            g.DrawString(Inf, DisIconFont, pen.Brush, new Drawing.Point(0,0));
            ico = (bufferedimage as Bitmap).GetHicon();

            g.Dispose();
            return Icon.FromHandle(ico);
        }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324792594&siteId=291194637