问题
What I have is R:255 G:181 B:178, and I am working in C# (for WP8, to be more specific)
I would like to convert this to a hex number to use as a color (to set the pixel color of a WriteableBitmap). What I am doing is the following:
int hex = (255 << 24) | ((byte)R << 16) | ((byte)G << 8) | ((Byte)B<<0);
But when I do this, I just get blue.
Any ideas what I am doing wrong?
Also, to undo this, to check the RGB values, I am going:
int r = ((byte)(hex >> 16)); // = 0
int g = ((byte)(hex >> 8)); // = 0
int b = ((byte)(hex >> 0)); // = 255
回答1:
Try the below:
using System.Drawing;
Color myColor = Color.FromArgb(255, 181, 178);
string hex = myColor.R.ToString("X2") + myColor.G.ToString("X2") + myColor.B.ToString("X2");
回答2:
You can use a shorter string format to avoid string concatenations.
string.Format("{0:X2}{1:X2}{2:X2}", r, g, b)
回答3:
Using string interpolation, this can be written as:
$"{r:X2}{g:X2}{b:X2}"
回答4:
Greetings fellow humans,
//Red Value
int integerRedValue = 0;
//Green Value
int integerGreenValue = 0;
//Blue Value
int integerBlueValue = 0;
string hexValue = integerRedValue.ToString("X2") + integerGreenValue.ToString("X2") + integerBlueValue.ToString("X2");
来源:https://stackoverflow.com/questions/13354892/converting-from-rgb-ints-to-hex