Add and split color in C #

I would like to create 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 will not compile because FromRGB() is required 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 anybody help me?

+6
source share
2 answers

Arithmetic operations on the byte (and short) give the result int. You must insert the entire expression in parentheses and do the following:

 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 it from 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)); 
+9
source

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; 

Notice I have not tried this, but I got it from MSDN:

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

UPDATE

I checked my last edit and it works.

+4
source

All Articles