使用特定的 alpha 透明度级别在 C# 中将图像放置在图像上

wil*_*oup 0 c# transparency alpha image

我希望能够将图像放置在图像上,但对叠加图像应用特定级别的透明度。

这是我到目前为止所拥有的:

    private static Image PlaceImageOverImage(Image background, Image overlay, int x, int y, int alpha)
    {
        using (Graphics graphics = Graphics.FromImage(background))
        {
            graphics.CompositingMode = CompositingMode.SourceOver;
            graphics.DrawImage(overlay, new Point(x, y));
        }

        return background;
    }
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激。

Jer*_*gen 5

您可以使用 ColorMatrix 来实现此目的:

private static Image PlaceImageOverImage(Image background, Image overlay, int x, int y, float alpha)
{
    using (Graphics graphics = Graphics.FromImage(background))
    {
        var cm = new ColorMatrix();
        cm.Matrix33 = alpha;

        var ia = new ImageAttributes();
        ia.SetColorMatrix(cm);

        graphics.DrawImage(
            overlay, 
            // target
            new Rectangle(x, y, overlay.Width, overlay.Height), 
            // source
            0, 0, overlay.Width, overlay.Height, 
            GraphicsUnit.Pixel, 
            ia);
    }

    return background;
}
Run Code Online (Sandbox Code Playgroud)

注意:alpha 是浮点数 (0...1)

PS:我宁愿创建一个新的位图并将其返回,而不是更改现有的位图。(并返回它) >>>这是关于函数式编程的。