how to remove duplicate char from ARGB

50 Views Asked by At

I am trying to get hex form rgb colors

public string GetCssValue(IWebElement iwe, string cssValue)
{
    var value = iwe.GetCssValue(cssValue);
    string[] numbers = value.Replace("rgba(", "").Replace(")", "").Split(",");

    int a = int.Parse(numbers[0]);
    int r = int.Parse(numbers[1]);
    int g = int.Parse(numbers[2]);
    int b = int.Parse(numbers[3]);

    Color myColor = Color.FromArgb(a, r, g, b);

    string hex = "#" + myColor.A.ToString("X2") + myColor.R.ToString("X2") + 
        myColor.G.ToString("X2") + myColor.B.ToString("X2");

here hex is gets the value #FFEEEE01 while my css on the page is #fee so that I can compare two strings (expected,actual)

how can I get the #fee as my hex value. and what does this X2 represent here

1

There are 1 best solutions below

0
Rufus L On

A quick way to change your code to return the value would be to only concatenate the first character from the RGB values:

string hex = "#" + myColor.R.ToString("X2")[0] + myColor.G.ToString("X2")[0] + 
    myColor.B.ToString("X2")[0];

But, since only a subset of 6-digit codes can be accurately converted to 3-digit codes (only those with repeating characters), it might be helpful to write a helper method to convert the values:

public string GetThreeDigitRGB(Color color)
{
    // Get the 2-character RGB color codes
    var r = color.R.ToString("X2");
    var g = color.G.ToString("X2");
    var b = color.B.ToString("X2");

    // Every color must have a repeating character for its code, otherwise we return null
    return r[0] == r[1] && g[0] == g[1] && b[0] == b[1]
        ? $"#{r[0]}{g[0]}{b[0]}"
        : null;
}

Then your original code could be modified to create a Color object from the input and pass it to our helper method above to get the 3-digit code (also note the change where we get the color values in the order RGBA, which is how they're passed in):

public string GetCssValue(IWebElement iwe, string cssValue)
{
    var value = iwe.GetCssValue(cssValue);
    string[] numbers = value.Replace("rgba(", "").Replace(")", "").Split(",");

    // Note the change to get the colors in the correct order
    int r = int.Parse(numbers[0]);
    int g = int.Parse(numbers[1]);
    int b = int.Parse(numbers[2]);
    int a = int.Parse(numbers[3]);

    // Create a color from the values
    Color myColor = Color.FromArgb(a, r, g, b);

    // Call our helper method to get the three digit code from the color
    return GetThreeDigitRGB(myColor);
}