Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

Edit:
If I set a solid color as background on the Graphics object, then the text transparency works, but I need it to be truly transparent in the result png file, not just transparent against a solid background color in the image. This problem occurs also if I set a partial transparent color as background like this:

lGraphic.Clear(Color.FromArgb(100, 0, 255, 0))

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.

like image 667
awe Avatar asked Oct 22 '25 14:10

awe


1 Answers

Set the TextRenderingHint to either SingBitPerPixel or SingleBitPerPixelGridFit:

lGraphic.TextRenderingHint = Drawing.Text.TextRenderingHint.SingleBitPerPixel
like image 107
Chris Haas Avatar answered Oct 25 '25 03:10

Chris Haas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!