[英]convert RGB int value to Hex format with 0x prefix in c#
I am trying to convert an RGB value to hex format in c# using this code : 我正在尝试使用以下代码在C#中将RGB值转换为十六进制格式:
int ColorValue = Color.FromName("mycolor").ToArgb();
string ColorHex = string.Format("{0:x6}", ColorValue);
The colorHex
value likes this format ffffff00
but i need to change it like this : 0x0000
.how can i do that? colorHex
值喜欢这种格式ffffff00
但是我需要像这样更改它: 0x0000
我该怎么做?
Best regards 最好的祝福
I am so new in c# form application . 我在c#表单应用程序中很新。
Just add the 0x
part yourself in the format string: 只需自己在格式字符串中添加
0x
部分:
// Local variable names to match normal conventions.
// Although Color doesn't have ToRgb, we can just mask off the top 8 bits,
// leaving RGB in the bottom 24 bits.
int colorValue = Color.FromName("mycolor").ToArgb() & 0xffffff;
string colorHex = string.Format("0x{0:x6}", colorValue);
If you want capital hex values instead of lower case, use "0x{0:X6}"
instead. 如果要使用大写十六进制值而不是小写字母,请改用
"0x{0:X6}"
。
If you want only the 3 bytes that define the RGB part of the color you could try this 如果只需要3个字节来定义颜色的RGB部分,则可以尝试以下操作
Color c = Color.FromName("mycolor");
int ColorValue = (c.R * 65536) + (c.G * 256) + c.B;
string ColorHex = string.Format("0x{0:X6}", ColorValue);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.