[英]How to convert RGB int values to string color
谁能告诉我如何在C#中将三个int值r, g, b
转换为字符串颜色(六值)
尝试这个
string s = Color.FromArgb(255, 143, 143, 143).Name;
int red = 255;
int green = 255;
int blue = 255;
string theHexColor = "#" + red.ToString("X2") + green.ToString("X2") + blue.ToString("X2");
RGB到十六进制:
string hexColor = string.Format("0x{0:X8}", Color.FromArgb(r, g, b).ToArgb());
十六进制为Rgb:
int rgbColor = int.Parse("FF", System.Globalization.NumberStyles.AllowHexSpecifier);
请找到以下扩展方法:
public static class ColorExtensions
{
public static string ToRgb(this int argb)
{
var r = ((argb >> 16) & 0xff);
var g = ((argb >> 8) & 0xff);
var b = (argb & 0xff);
return string.Format("{0:X2}{1:X2}{2:X2}", r, g, b);
}
}
这是您的用法:
int colorBlack = 0x000000;
int colorWhite = 0xffffff;
Assert.That(colorBlack.ToRgb(), Is.EqualTo("000000"));
Assert.That(colorWhite.ToRgb(), Is.EqualTo("FFFFFF"));
为PowerPoint形状对象的Fill.ForeColor.RGB成员解决了此问题,我发现RGB值实际上是BGR(蓝色,绿色,红色),因此C#PowerPoint插件将Fill.ForeColor.RGB转换为字符串的解决方案是:
string strColor = "";
var b = ((shpTemp.Fill.ForeColor.RGB >> 16) & 0xff);
var g = ((shpTemp.Fill.ForeColor.RGB >> 8) & 0xff);
var r = (shpTemp.Fill.ForeColor.RGB & 0xff);
strColor = string.Format("{0:X2}{1:X2}{2:X2}", r, g, b);
我所做的如下:
int reducedRed = getRed(long color)/128; // this gives you a number 1 or 0.
int reducedGreen = getGreen(long color)/128; // same thing for the green value;
int reducedBlue = getBlue(long color)/128; //same thing for blue
int reducedColor = reducedBlue + reducedGreen*2 + reducedRed*4 ;
// reduced Color is a number between 0 -7
一旦获得了reduceColor,就可以在0到7之间进行切换。
switch(reducedColor){
case 0: return "000000"; // corresponds to Black
case 1: return “0000FF"; // corresponds to Blue
case 2: return "00FF00"; // corresponds to Green
case 3: return "00FFFF"; // corresponds to Cyan
case 4: return “FF0000"; // corresponds to Red
case 5: return "FF00FF"; //corresponds to Purple
case 6: return "FFFF00"; //corresponds to Yellow
case 7: return “FFFFFF"; //corresponds to White
}
Ø
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.