C# 2.0, GDI+ images & opacity

And don't know if this post belongs to this forum, but i'll ask anyway...

I'm making a small game as a test with GDI+ (C# 2.0). I had this question: is there an easy way to draw an Image object to Graphics with different opacity

I don't mean the transparency key thing, but the whole image should be half visible, and trasparency color of course not visible at all. I managed to alter the opacity of the image with getpixel and setpixel, but I'd like to know if there was a way to avoid pixel manipulation (since it takes time).


Answer this question

C# 2.0, GDI+ images & opacity

  • Ivan Ooi

    Great!

    Thank You very much for the answer.

    btw, Is there some documentation available, where I can check which element means which 4x4 matrix i would understand (RGBA), but 5x5 what is the fift element ( )

  • Sherrill34643

    Some of DrawImage methods take an ImageAttributes parameter. The ImageAttributes class has a method called SetColorMatrix. Using that you can do anything with the colors of your image including modifying the alpha channel.

    For your case I think the following color matrix sould do:

    private static ColorMatrix colorMatrix = new ColorMatrix(
    new float[][]
    {
    new float[] {1, 0, 0, 0, 0},
    new float[] {0, 1, 0, 0, 0},
    new float[] {0, 0, 1, 0, 0},
    new float[] {0, 0, 0, 0.50f, 0},
    new float[] {0, 0, 0, 0, 1}
    });

    Note the 0.5f value. That's the opacity.

    protected void DrawTransparentImage(Graphics g, Rectangle rc, Image image)
    {
    using (ImageAttributes attrs = new ImageAttributes())
    {
    attrs.SetColorMatrix(colorMatrix);

    g.DrawImage(image, rc, 0, 0, image.Width, image.Height,
    GraphicsUnit.Pixel, attrs);
    }
    }


  • sumesh_tewatia

  • andyboy

    Thanks again

  • C# 2.0, GDI+ images & opacity