Search code examples
c#graphicsgdi+transparencydrawstring

Drawing "transparent" text via C# Graphics, but in a way that it turns the drawn text to be "missing" so it's transparent in the resulting image


I am looking to draw a string on a DC (Graphics - I am using C#) - but I want the drawn text to be "deleted" from the image so that what's left is essentially a cut-out of the text.

If I was to DrawString with a transparent brush obviously nothing would have happened.

Is there a way of drawing something like that, or do I need to use 2 DCs and BitBlt with some combination of NOTs or XOR or whatever (I did similar things years ago, but was wondering if there's an easiery way)?


Solution

  • You could set Graphics.CompositingMode to CompositingMode.SourceCopy - but I'm not sure if that will work with transparent content.

    The way around this is to:

    1. Draw your text to a separate image using red brush over black background.
    2. Iterate over each pixel of text image and target image...
    3. ...manually set target image pixel color's Alpha value according to text's image Red component.

    If speed is not a concern and you deal with small bitmaps, you can use GetPixel and SetPixel methods. But I would recommend using LockBits to access BitmapData directly and process pixels in a byte array. This is fast and not-so-hard-to-implement solution, although you'll have to deal with "unsafe" code (or use the Marshal class).

    LockBits reference on MSDN

    Marshal reference on MSDN