6

我想从两种颜色生成中间颜色:

Color Middle = Color.FromRGB(Color.FromRgb( Color1.R + Color2.R) / 2, (Color1.G + Color2.G) / 2, (Color1.B + Color2.B) / (2);

此代码不会编译,因为FromRGB()需要一个byte.

所以我尝试了这个:

Color myColorMiddle = Color.FromRgb((byte)(Color1.R + Color2.R) / (byte)2, (byte)(Color1.G + Color2.G) / (byte)2, (byte)(Color1.B + Color2.B) / (byte)2);

但我得到同样的错误。任何人都可以帮助我吗?

4

2 回答 2

9

对字节(和短)的算术运算产生一个 int 结果。您必须将整个表达式放在括号中并强制转换:

Color myColorMiddle = Color.FromRgb((byte)((Color1.R + Color2.R) / 2), (byte)((Color1.G + Color2.G) / 2), (byte)((Color1.B + Color2.B) / 2));

如果您将其提取到函数中,您的代码会更清晰:

byte Average(byte a, byte b)
{
    return (byte)((a + b) / 2);
}

然后您的代码如下所示:

Color myColorMiddle = Color.FromRgb(Average(Color1.R, Color2.R), Average(Color1.G, Color2.G), Average(Color1.B, Color2.B));
于 2013-04-12T21:15:43.073 回答
4

If you are using System.Windows.Media.Color, I think you can do this:

  Color start = Color.FromRgb(255, 0, 0);
  Color end = Color.FromRgb(0, 255, 0);
  Color middle = start + (end - start) * 0.5F;

Note, I did not try this, but I did get it from MSDN:

http://msdn.microsoft.com/en-us/library/system.windows.media.color.aspx

UPDATE

I have tested my most recent edit and it does work.

于 2013-04-12T21:28:21.683 回答