【问题标题】:How to paint a color with alpha over an image - C#/.NET如何在图像上使用 alpha 绘制颜色 - C#/.NET
【发布时间】:2013-09-23 16:44:25
【问题描述】:

我要做的是在现有图像上绘制具有某种程度不透明度的纯色和/或图案。我相信从我读过的内容来看,这将涉及一个位图掩码。我看到的使用位图蒙版作为不透明蒙版的示例仅显示它们用于以某种方式裁剪图像,并且我想将其用于绘画。这基本上是我想要完成的:

第一个图像正在加载并使用 DrawImage 绘制到派生的 Canvas 类上。我正在尝试完成您在第三张图片中看到的内容,第二张是我可能使用的蒙版示例。两个关键点是第三张图像中的蓝色表面需要是任意颜色,并且它需要一些不透明度,以便您仍然可以看到底层图像上的阴影。这是一个简单的例子,其他一些对象有更多的表面细节和更复杂的蒙版。

【问题讨论】:

  • 您正在开发牙科应用程序吗?太棒了!
  • 完全不清楚为什么要使用面具。只需使用 Graphics.FillRectangle(),使用您使用 alpha 小于 255 的 Color 创建的 SolidBrush。
  • Paint.NET 的最后一个开源版本——code.google.com/p/openpdn/source/checkout
  • @HansPassant 面具似乎不是一个矩形 - 似乎他希望能够对比任意区域。
  • 好吧,那么 Graphics.FillPath() 或 FillRegion() 应该符合要求。

标签: c# .net image bitmap


【解决方案1】:

颜色矩阵在这里很有用:

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);
  }
}

Matrix 声明中的 0.5f 值是 alpha 值。

【讨论】:

  • 这正是我正在寻找的,非常感谢您提供的信息!我正在尝试将其调整为在 WPF Canvas 类的 OnRender 函数中工作,该函数通过 DrawingContext 而不是 PaintEventArgs,并且 DrawingContext.DrawImage 函数没有接受 ImageAttributes 的版本。你知道我如何从 DrawingContext 中获取适当的函数吗?
  • @amnesia 错过了 WPF 的部分。见WriteableBitmap。我不能提供更多的东西——我的背景是 WinForms。
  • 我的错漏掉了。我真的很感谢你在这里的出色努力,你肯定让我朝着正确的方向前进。
  • 我们最终只是将控件移植到 WinForms 并在 WPF 项目中使用 WindowsFormsHost。只是想再次说声谢谢,你为我节省了很多时间。
猜你喜欢
  • 1970-01-01
  • 2014-09-16
  • 1970-01-01
  • 1970-01-01
  • 2020-01-24
  • 2020-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多