分享
三行代码  ›  专栏  ›  技术社区  ›  Illud

如何将ARGB转换为RGB和HEX?

c#
  •  -1
  • Illud  · 技术社区  · 1 周前

    Bitmap bmp = new Bitmap(1, 1);
    using (Graphics g = Graphics.FromImage(bmp))
    {
        g.CopyFromScreen(System.Windows.Forms.Cursor.Position, new Point(0, 0), new Size(1, 1));
    }
    System.Drawing.Color pixel = bmp.GetPixel(0, 0);
    label3.Text = bmp.GetPixel(0, 0).ToString();
    Point p = new Point();
    p.X = (this.Width / 2) - (label3.Width / 2);
    p.Y = label3.Top;
    label3.Location = p;
    pictureBox1.BackColor = pixel;
    rgbColor = pixel.ToString(); // I want this to be RGB and also HEX 
    this.Invalidate();
    
    2 回复  |  直到 1 周前
        1
  •  1
  •   John    1 周前

    您应该能够使用这两种方法获得所需的Alpha/Red/Green组合:

    public static string GetARG(Color c)
    {
        return string.Format("{0},{1},{2}", c.A, c.R, c.G);
    }
    
    public static string GetARGHex(Color c)
    {
        return string.Format("{0:X2}{1:X2}{2:X2}", c.A, c.R, c.G);
    }
    

    string arg = GetARG(pixel); // 255,235,156
    string argHex = GetARGHex(pixel); // FFEB9C
    

    Try it online

        2
  •  0
  •   Michael Randall    1 周前

    应该很容易

    可拓方法

    private static String ToRgbHex(this Color c) 
        => $"{c.R:X2}{c.G:X2}{c.B:X2}";
    

    var myAweseomHexValue = pixel.ToRgbHex();