Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding transparency to Graphics.Draw

Tags:

c#

Is it possible to draw a Graphics in C# with a transparency e.g. 50%?

My actual code looks like this:

Image myBitmap = new Bitmap((int)sizeX,(int)sizeY);
Graphics myGraphics = Graphics.FromImage(myBitmap);

Pen outerPenColor = new Pen(Color.Black, 1);

myGraphics.DrawRectangle(outerPenColor, 1.0, 2.0, 3.0, 4.0);

this all works fine, but I want to have a transparent black, is this possible?

like image 453
gurehbgui Avatar asked Oct 24 '25 20:10

gurehbgui


1 Answers

The Graphics context and Bitmap objects supports transparency by default. The only thing you have to do is draw colors that are not opaque. There is an overload for the static method Color.FromArgb that takes an alpha value and a color and returns a Color that has the transparency you specified. The alpha value is a value between 0 (fully transparent) to 255 (fully opaque). For example:

// 75% opaque (25% transparent) Red
var semiRed = Color.FromArgb(191, Color.Red);
// 50% opaque (50% transparent) Black
var semiBlack = Color.FromArgb(128, Color.Black);

Now you can use that semi-transparent black as the color for your Pen and draw semi-transparent lines:

Pen outerPenColor = new Pen(semiBlack, 1);
myGraphics.DrawRectangle(outerPenColor, 1.0, 2.0, 3.0, 4.0);
like image 119
Daniel A.A. Pelsmaeker Avatar answered Oct 26 '25 11:10

Daniel A.A. Pelsmaeker