I would like to generate a middle color from two colors:
Color Middle = Color.FromRGB(Color.FromRgb( Color1.R + Color2.R) / 2, (Color1.G + Color2.G) / 2, (Color1.B + Color2.B) / (2);
This code won't compile because FromRGB()
needs a byte
.
So I tried this:
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);
But I get the same error. Can anyone help me please?
Arithmetic operations on byte (and short) yield an int result. You have to put the entire expression in parentheses and cast that:
Color myColorMiddle = Color.FromRgb((byte)((Color1.R + Color2.R) / 2), (byte)((Color1.G + Color2.G) / 2), (byte)((Color1.B + Color2.B) / 2));
Your code will be cleaner if you extract this to a function:
byte Average(byte a, byte b)
{
return (byte)((a + b) / 2);
}
Then your code looks like this:
Color myColorMiddle = Color.FromRgb(Average(Color1.R, Color2.R), Average(Color1.G, Color2.G), Average(Color1.B, Color2.B));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With