When I draw on a Bitmap Graphics an image that have translucent pixels, and then drawing bitmap on the screen, these pixels become black.
At the same time, purely transparent pixels around the image remain transparent.
Who knows how to fix this?
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Drawing.Drawing2D;
namespace SimpleTest
{
public partial class Form12_BitmapAlpha : Form
{
public Form12_BitmapAlpha()
{
InitializeComponent();
}
private void Panel1_Paint(object sender, PaintEventArgs e)
{
//Back
e.Graphics.FillRectangle(new SolidBrush(Color.Coral), new Rectangle(5, 5, 25, 85));
// 1
RadioButtonRenderer.DrawRadioButton(e.Graphics, new Point(10, 10), RadioButtonState.CheckedNormal);
//2
Size cbSize = RadioButtonRenderer.GetGlyphSize(e.Graphics, RadioButtonState.CheckedNormal);
Bitmap cbBitmap = new Bitmap(cbSize.Width, cbSize.Height);
using (Graphics offscreen = Graphics.FromImage(cbBitmap))
{
//offscreen.CompositingMode = CompositingMode.SourceCopy; //doesn't work
//offscreen.Clear(Color.Transparent); //it doesn't help
RadioButtonRenderer.DrawRadioButton(offscreen, new Point(0, 0), RadioButtonState.CheckedNormal);
}
e.Graphics.DrawImage(cbBitmap, new Point(10, 40));
//3
RadioButtonRenderer.DrawRadioButton(e.Graphics, new Point(10, 70), RadioButtonState.CheckedNormal);
Bitmap cbBitmap1 = new Bitmap(20, 20);
using (Graphics offscreen = Graphics.FromImage(cbBitmap1))
{
offscreen.FillRectangle(new SolidBrush(Color.FromArgb(128, Color.Red)), new Rectangle(2, 2, 16, 16));
}
e.Graphics.DrawImage(cbBitmap1, new Point(0, 65));
}
}
}
In the first part of the code, (under //1) I draw directly on the Graphics of the Panel and you can see that the edges of the RadioButton are drawn in a semi-transparent color.
In the second part of the code (under //2), I draw the same thing, but through a Bitmap object. Here the border is drawn black.
And in the third part (under //3), I draw a translucent square on a Bitmap and then draw this Bitmap on the screen to show that Bitmap supports translucent areas.
and the result