Search code examples
c#visual-studio-2010kmlkmzcolordialog

How to Convert ColorDialog color to KML color format


I’m looking for a way to convert the color code returned by a ColorDialog Box in C# into the color format utilized by KML/KMZ file formats. Any info would be greatly appreciated!!


Solution

  • After hours of research I have answered my own question.

    Kml uses an 8 digit HEX color format. The traditional Hex format for red looks like #FF0000. In Kml, red would look like this FF0000FF. The first 2 digits are for opacity(alpha). Color format is in AABBGGRR. I was looking for a way to set the color as well as the opacity and return it in a string to be placed in the attribute of a KML. Here is my solution.

    string color
    string polyColor;
    int opacity;
    decimal percentOpacity;
    string opacityString;
    
    //This allows the user to set the color with a colorDialog adding the chosen color to a string in HEX (without opacity (BBGGRR))
    private void btnColor_Click(object sender, EventArgs e)
    {
        if (colorDialog1.ShowDialog() == DialogResult.OK)
        {
            btnColor.BackColor = colorDialog1.Color;
            Color clr = colorDialog1.Color;
            color = String.Format("{0:X2}{1:X2}{2:X2}", clr.B, clr.G, clr.R);
        }
    }
    
    //This method takes the Opacity (0% - 100%) set by a textbox and gets the HEX value. Then adds Opacity to Color and adds it to a string.
    private void PolyColor()
    {
        percentOpacity = ((Convert.ToDecimal(txtOpacity.Text) / 100) * 255);
        percentOpacity = Math.Floor(percentOpacity);  //rounds down
        opacity = Convert.ToInt32(percentOpacity);
        opacityString = opacity.ToString("x");
        polyColor = opacityString + color;
    
    }
    

    Im open for more efficient ways to get the color value