合并2种颜色以制作透明覆盖层?

时间:2010-04-22 21:41:15

标签: c# .net image

我有两个System.Windows.Media.Color(a和b),需要得到一个并将置于b 以模拟透明度。在我的合并方法中使用:

public static Image Merge(Image a,Image b)
{

    for(int x=0;x < b.Width;x++ )
    {
        for (int y = 0; y < b.Height; y++)
        {
            a.SetPixel(x, y, b.GetPixel(x, y));
        }
    }
    return a;
}

帮助感谢!!

解决方案:

        public static Image Merge(Image a,Image b)
        {

            for(int x=0;x < b.Width;x++ )
            {
                for (int y = 0; y < b.Height; y++)
                {
                    a.SetPixel(x, y, Mix(a.GetPixel(x, y), b.GetPixel(x, y), .5f));
                    //a.SetPixel(x, y,b.GetPixel(x, y));
                }
            }

            return a;
        }

        public static Color Mix(Color from, Color to, float percent)
        {
            float amountFrom = 1.0f - percent;

            return Color.FromArgb(
            (byte)(from.A * amountFrom + to.A * percent),
            (byte)(from.R * amountFrom + to.R * percent),
            (byte)(from.G * amountFrom + to.G * percent),
            (byte)(from.B * amountFrom + to.B * percent));
        }

我在Mix方法中发现了一个舍入错误,在使用Math.Round()时解决:

public static Color Mix(Color from,Color to,float percent)     {         float amountFrom = 1.0f - percent;

    return Color.FromArgb(
    (byte)Math.Round(from.A * amountFrom + to.A * percent),
    (byte)Math.Round(from.R * amountFrom + to.R * percent),
    (byte)Math.Round(from.G * amountFrom + to.G * percent),
    (byte)Math.Round(from.B * amountFrom + to.B * percent));
}

1 个答案:

答案 0 :(得分:4)

找到this article,其中包含以下方法:

public static Color Mix(Color from, Color to, float percent)
{
    float amountFrom = 1.0f - percent;

    return Color.FromArgb(
    (int)(from.A * amountFrom + to.A * percent),
    (int)(from.R * amountFrom + to.R * percent),
    (int)(from.G * amountFrom + to.G * percent),
    (int)(from.B * amountFrom + to.B * percent));
}

这样称呼:

a.SetPixel(x, y, Mix(a.GetPixel(x, y), b.GetPixel(x, y), .5f));

您可能需要稍微使用该功能(甚至可能更改它),但我认为它可以让您获得您正在寻找的结果。