8

How to convert integer to color in WPF? For example, I want to convert 16711935 to color.

How to do something like below in windows forms, in WPF?

myControl.Background = Color.FromArgb(myColorInt);
1
  • @GrantWinney WPF Color.FromArgb requires 4 parameters namely byte a, byte r, byte g, byte b. Commented Jan 21, 2014 at 2:30

3 Answers 3

17

Use the BitConverter Class to convert your value to a Byte Array, that way you do not need to import another namespace.

byte[] bytes = BitConverter.GetBytes(16711935);
this.Background = new SolidColorBrush( Color.FromArgb(bytes[3],bytes[2],bytes[1],bytes[0]));
Sign up to request clarification or add additional context in comments.

3 Comments

Good way of doing it. Note however that if the integer contains argb values in that order - with alpha occupying the leftmost bits, then you may need the parameters to Color.FromArgb the other way round... Color.FromArgb(bytes[3],bytes[2],bytes[1],bytes[0])
Good answer though as Simon says the bytes do need reversing if you are converting an int outputed by the System.Drawing.Color.ToArgb method.
@Simon You are right, just verified myself and edited the answer of Mark
4

You want to use System.Drawing.Color, not System.Windows.Media.Color:

var myColor = System.Drawing.Color.FromArgb(16711935);

Ooookay, not sure this is very pretty, but you could convert from one Color class to the other, then use that in the SolidColorBrush ctor:

myControl.Background = new SolidColorBrush(
  System.Windows.Media.Color.FromArgb(myColor.A,myColor.R,myColor.G,myColor.B));

2 Comments

I have edited the question. Above gives "Cannot implicitely convert "system.drawing.color" to "System.windows.Media.Brush" "error.
Good solution. For me at least, it is easier to follow what is going on in a glance, as opposed to using the accepted answer with the byte array.
1

The System.Windows.Media.Color structure has similar methods but they have parameters of type Byte. You can use the BitConverter class to convert between an array of Bytes and an Int32.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.