views:

264

answers:

2

This is a .NET application on Windows forms using C++/CLI. I have a JPEG that I want to paint in my client area to represent an object. On some occasions -- like when the user is dragging objects around -- I'd like to draw the object with some transparency.

What are the various available ways to do this?

+1  A: 

I would try creating a second image with 50% transparency. As a System.Drawing.Bitmap you can get and set its Pixels (GetPixel, SetPixel):

Color pixelColor = bitmap.GetPixel(x,y);
Color transparentPixelColor = MakePixelTransparent(pixelColor);
bitmap.SetPixel(x,y,transparentPixelColor);

MakePixelTransparent() would set the alpha value in the supplied color (something like getting the ARGB-value, setting the A-byte and create a new color out of the new Argb-value).

Thats what I would try (I didn't though)...

EDIT: I tried it now, out of curiosity:

Bitmap bitmap = new Bitmap( "YourImageFile.jpg" );
bitmap.MakeTransparent();
for ( int y = 0; y < bitmap.Height; y++ ) {
    for ( int x = 0; x < bitmap.Width; x++ ) {
        Color pixelColor = bitmap.GetPixel( x, y );
        Color transparentPixelColor = Color.FromArgb( pixelColor.ToArgb() & 0x7fffffff );
        bitmap.SetPixel( x, y, transparentPixelColor );
    }
}
e.Graphics.DrawImage( bitmap, 10, 10 );

Works. That way you can also make only parts of the image transparent...

EricSchaefer
Ouch, that is slow... looping using GetPixel and SetPixel. Here I would investigage the use of a byte[] or int*.http://www.codeproject.com/KB/GDI-plus/pointerlessimageproc.aspx
Dykam
Well, I hacked it in about 3 minutes. I did not claim it would be anywhere near to fast.
EricSchaefer
+1  A: 

This should do it:

:)

Vulcan Eager