Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add and divide color in C#

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?

like image 820
Walter Fabio Simoni Avatar asked Apr 12 '13 21:04

Walter Fabio Simoni


2 Answers

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));
like image 130
phoog Avatar answered Oct 19 '22 04:10

phoog


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.

like image 4
wageoghe Avatar answered Oct 19 '22 04:10

wageoghe