Using C# I was trying to develop the following two. The way I am doing it may have some problem and need your kind advice. In addition, I dont know whether there is any existing method to do the same.
private static String HexConverter(System.Drawing.Color c)
{
String rtn = String.Empty;
try
{
rtn = "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}
catch (Exception ex)
{
//doing nothing
}
return rtn;
}
private static String RGBConverter(System.Drawing.Color c)
{
String rtn = String.Empty;
try
{
rtn = "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}
catch (Exception ex)
{
//doing nothing
}
return rtn;
}
Thanks.
I found an extension method that works quite well
Ref: https://social.msdn.microsoft.com/Forums/en-US/4c77ba6c-6659-4a46-920a-7261dd4a15d0/how-to-convert-rgba-value-into-its-equivalent-hex-code?forum=winappswithcsharp
For hexadecimal code try this
& 0x00FFFFFF
For RGB one
Red
,Green
,Blue
valuesImplementation
I'm failing to see the problem here. The code looks good to me.
The only thing I can think of is that the try/catch blocks are redundant -- Color is a struct and R, G, and B are bytes, so c can't be null and
c.R.ToString()
,c.G.ToString()
, andc.B.ToString()
can't actually fail (the only way I can see them failing is with aNullReferenceException
, and none of them can actually be null).You could clean the whole thing up using the following:
e.g.
This can avoid the KnownColor trick.
You could keep it simple and use the native color translator:
Then break the three color pairs into integer form:
If you can use C#6, you can benefit from Interpolated Strings and rewrite @Ari Roth's solution like this:
C# 6 :
Also:
this
to use them as extensions methods.string
instead of the class name.