amnesia
amnesia

Reputation: 1988

How to paint a color with alpha over an image - C#/.NET

What I'm trying to do is paint a solid color and/or pattern with some degree of opacity over an existing image. I believe from what I've read this will involve a bitmap mask. The examples I've seen using bitmap masks as opacity masks only show them used against images to crop them a certain way, and I want to use it for painting. Here is basically what I'm trying to accomplish:

1. image, 2. mask, 3. result

The first image is being loaded and drawn onto a derived Canvas class using DrawImage. I'm trying to accomplish what you see in the 3rd image, the 2nd is an example of a mask I might use. The two key points being that the blue surface in the 3rd image needs to be any arbitrary color, and it needs some opacity so that you can still see the shading on the underlying image. This is kind of a simple example, some of the other objects have much more surface detail and much more complicated masks.

Upvotes: 2

Views: 1222

Answers (1)

LarsTech
LarsTech

Reputation: 81610

A color matrix can be useful here:

private Image tooth = Image.FromFile(@"c:\...\tooth.png");
private Image maskBMP = Image.FromFile(@"c:\...\toothMask.png");

protected override void OnPaint(PaintEventArgs e) {
  base.OnPaint(e);

  e.Graphics.DrawImage(tooth, Point.Empty);

  using (Bitmap bmp = new Bitmap(maskBMP.Width, maskBMP.Height, 
                                 PixelFormat.Format32bppPArgb)) {

    // Transfer the mask
    using (Graphics g = Graphics.FromImage(bmp)) {
      g.DrawImage(maskBMP, Point.Empty);
    }

    Color color = Color.SteelBlue;
    ColorMatrix matrix = new ColorMatrix(
      new float[][] {
        new float[] { 0, 0, 0, 0, 0},
        new float[] { 0, 0, 0, 0, 0},
        new float[] { 0, 0, 0, 0, 0},
        new float[] { 0, 0, 0, 0.5f, 0},
        new float[] { color.R / 255.0f,
                      color.G / 255.0f,
                      color.B / 255.0f,
                      0, 1}
      });

    ImageAttributes imageAttr = new ImageAttributes();
    imageAttr.SetColorMatrix(matrix);

    e.Graphics.DrawImage(bmp,
                         new Rectangle(Point.Empty, bmp.Size),
                         0,
                         0,
                         bmp.Width,
                         bmp.Height,
                         GraphicsUnit.Pixel, imageAttr);
  }
}

The 0.5f value in the Matrix declaration is the alpha value.

enter image description here

Upvotes: 2

Related Questions