David Rutten
David Rutten

Reputation: 4806

Draw an image with custom transparency in GDI+

I'm drawing lots of images (all of them dimensions=24x24 pixelformat=32BppPArgb) onto a Control using a Drawing.Graphics object and the DrawImage() function. It's possible to zoom out in my application which means that the Graphics object has a Transform Matrix attached to it which controls both zooming and panning.

There's no point in drawing these icons when the zoom drops below 50%, but I'd like to make the transition from drawing icons to not drawing icons smoother. I.e., starting at 70%, icons should be drawn with an additional transparency factor so that they will become completely transparent at 50%.

How can I draw a bitmap with an additional transparency without it taking significantly longer than DrawImage()?

Thanks, David

Upvotes: 4

Views: 2627

Answers (1)

Dan Byström
Dan Byström

Reputation: 9244

You just create an appropriate ColorMatrix, initialize a ImageAttributes object with it and pass that ImageAttributes object to one of the overloaded version of Graphics.DrawImage. This sample will give you 50% transparancy:

  float[][] matrixAlpha =
  {
   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.5f, 0}, 
   new float[] {0, 0, 0, 0, 1}
  }; 
  ColorMatrix colorMatrix = new ColorMatrix( matrixAlpha );

  ImageAttributes iaAlphaBlend = new ImageAttributes();
  iaAlphaBlend.SetColorMatrix(
   colorMatrix,
   ColorMatrixFlag.Default,
   ColorAdjustType.Bitmap );

Upvotes: 7

Related Questions