C# Converting delphi TColor to color (Hex)

前端 未结 2 1030
终归单人心
终归单人心 2021-01-18 23:37

\"enter

These numbers are stored in the Database. They origionate from Delphi code. Al

相关标签:
2条回答
  • 2021-01-19 00:03

    Delphi colors (TColor) are XXBBGGRR when not from a palette or a special color.

    See this article for more detail on the format (And other special cases). The article pointed by Christian.K also contains some details on the special cases.

    Standard colors

    To convert to a standard color you should use something like :

    var color = Color.FromArgb(0xFF, c & 0xFF, (c >> 8) & 0xFF, (c >> 16) & 0xFF);
    

    To convert to hex, :

    string ColorToHex(Color color)
    {
        return string.Format("#{0:X2}{1:X2}{2:X2}",
            color.R, color.G, color.B);
    }
    

    System colors

    For system colors (negative values in your database), they are simply the windows constants masked by 0x80000000.

    Thanks to David Heffernan for the info.

    Sample code

    Color DelphiColorToColor(uint delphiColor)
    {
        switch((delphiColor >> 24) & 0xFF)
        {
            case 0x01: // Indexed
            case 0xFF: // Error
                return Color.Transparent;
    
            case 0x80: // System
                return Color.FromKnownColor((KnownColor)(delphiColor & 0xFFFFFF));
    
            default:
                var r = (int)(delphiColor & 0xFF);
                var g = (int)((delphiColor >> 8) & 0xFF);
                var b = (int)((delphiColor >> 16) & 0xFF);
                return Color.FromArgb(r, g, b);
        }
    }
    
    void Main()
    {
        unchecked
        {
            Console.WriteLine(DelphiColorToColor((uint)(-2147483646)));
            Console.WriteLine(DelphiColorToColor(
                    (uint)KnownColor.ActiveCaption | 0x80000000
                ));
            Console.WriteLine(DelphiColorToColor(0x00FF8000));
        }
    }
    
    0 讨论(0)
  • 2021-01-19 00:22

    It looks like the numbers are the base-10 representation of Delphi TColor values.

    Delphi itself seems to provide some helper functions (e.g. GetRValue) to extract the respective read, green and blue values. You have to write something similar in c# yourself.

    Having the values you can assemble them into a hex string.

    string.Format("#{0:X2}{1:X2}{2:X2}", redComponent, greenComponent, blueComponent);
    

    Simply converting the integer value to a hex-string, padded or not, will most likely not do the right thing.

    UPDATE as commenter James L. points out, the order of the components is actually different for/in delphi. To generate a TColor-like value the order must be:

    string.Format("#{0:X2}{1:X2}{2:X2}", blueComponent, greenComponent, redComponent);
    
    0 讨论(0)
提交回复
热议问题