How to draw semi-transparent text on a graphics object?

Posted by awe on Stack Overflow See other posts from Stack Overflow or by awe
Published on 2010-03-15T12:53:25Z Indexed on 2010/03/15 12:59 UTC
Read the original article Hit count: 570

Filed under:
|
|
|
|

I want to draw a text with 32 bit transparency on a graphics object. When I try, I only get black color in the result.

If I try to draw a line with the same semitransparent color, it works perfectly.

I have this code:

lBitmap As New Bitmap(32, 32, PixelFormat.Format32bppArgb)
lGraphic As Graphics = Graphics.FromImage(lBitmap)

lGraphic.SmoothingMode = SmoothingMode.HighQuality
lGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic

lGraphic.Clear(Color.Transparent)

Dim lTestTransparencyColor As Color = Color.FromArgb(100, 140, 0, 230)
lGraphic.DrawLine(New Pen(lTestTransparencyColor), 0, 0, 32, 32)

lBrush As New SolidBrush(lTestTransparencyColor)
lGraphic.DrawString("A", New Font("Arial", 12), lBrush, 0, 0)

Dim lImage As Image = lBitmap
lImage.Save("D:\Test.png", Imaging.ImageFormat.Png)

The line is drawn with the transparency applied correctly, but the text is black with no transparency.

I was thinking it may be that SolidBrush does not support transparency, but I found a predefined brush named Transparent (Brushes.Transparent) that was a SolidBrush when I looked at it in debug. I tried to use Brushes.Transparent as the brush when drawing the text, and it was successfully not showing at all. That means I get full transparency to work, but not partial transparency.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about vb.net