How to convert color name to the corresponding hexadecimal representation?

前端 未结 5 1376
面向向阳花
面向向阳花 2020-12-19 13:56

For example:

blue 

converts to:

#0000FF

I wrote it as:

Color color = Color.FromName(\"blue\

相关标签:
5条回答
  • 2020-12-19 14:20

    You're half way there. Use .ToArgb to convert it to it's numberical value, then format it as a hex value.

    int ColorValue = Color.FromName("blue").ToArgb();
    string ColorHex = string.Format("{0:x6}", ColorValue);
    
    0 讨论(0)
  • 2020-12-19 14:22

    Ahmed's answer is close, but based on your comment, I'll just add a little more.

    The code that should make this work is:

    Color color = Color.FromName("blue");
    string myHexString = String.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
    

    Now you can do whatever you want with the string myHexString.

    0 讨论(0)
  • 2020-12-19 14:25
    var rgb = color.ToArgb() & 0xFFFFFF; // drop A component
    var hexString = String.Format("#{0:X6}", rgb);
    

    or just

    var hexString = String.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
    
    0 讨论(0)
  • 2020-12-19 14:29
    {
        Color color = Color.FromName("blue");
        byte g = color.G;
        byte b = color.B;
        byte r = color.R;
        byte a = color.A;
        string text = String.Format("Color RGBA values: red:{0x}, green: {1}, blue {2}, alpha: {3}", new object[]{r, g, b, a});
    

    // seriously :) this is simple:

        string hex = String.Format("#{0:x2}{1:x2}{2:x2}", new object[]{r, g, b}); 
    
    }
    
    0 讨论(0)
  • 2020-12-19 14:35

    You can use gplots package:

    library(gplots)
    col2hex("blue")
    # [1] "#0000FF"
    

    https://cran.r-project.org/web/packages/gplots/index.html

    Inside gplots package the code for col2hex function is:

    col2hex <- function(cname)
    {
        colMat <- col2rgb(cname)
        rgb(
            red=colMat[1,]/255,
            green=colMat[2,]/255,
            blue=colMat[3,]/255
        )
    }
    
    0 讨论(0)
提交回复
热议问题