简体   繁体   English

System.Drawing.Color转换FromArgb问题

[英]System.Drawing.Color convert FromArgb issue

I'm saving my color in db in int value. 我将颜色保存为int值。

int icolor = System.Drawing.Color.Red.ToArgb();
//result: -65536

When convert int to Color than lost property Color.Name. 当将int转换为Color时,将丢失属性Color.Name。 Must return "Red" but property return "ff000000". 必须返回“红色”,但属性返回“ ff000000”。 What I doing wrang? 我在做什么?

I need get this one - property Red but not hex value 我需要得到一个-红色属性,而不是十六进制值

尝试这个

System.Drawing.ColorTranslator.FromHtml("#" + "Hex value").Name

You're doing nothing wrong. 你没做错什么

ff in hex equals 255 which is the decimal value for the Red color, which is being returned by System.Drawing.Color.Red.ToArgb(); ff (十六进制)等于255,它是Red的十进制值,由System.Drawing.Color.Red.ToArgb();返回System.Drawing.Color.Red.ToArgb();

If you'd like to get the name of the color, use System.Drawing.Color.Red.Name 如果要获取颜色的名称,请使用System.Drawing.Color.Red.Name

string sRedColorName = System.Drawing.Color.Red.Name;

When convert int to Color than lost property Color.Name. 当将int转换为Color时,将丢失属性Color.Name。

Yes, that's correct. 对,那是正确的。 This is how the Color.Name property works. 这就是Color.Name属性的工作方式。 According to the documentation : 根据文档

This method returns either the user-defined name of the color, if the color was created from a name, or the name of the known color. 如果从名称创建颜色,则此方法返回用户定义的颜色名称,或者返回已知颜色的名称。 For custom colors, the RGB value is returned. 对于自定义颜色,返回RGB值。

So since you're creating a Color object from the integer (RGB) value—not its name—the Color structure doesn't recognize it as a named color. 因此,由于您是根据整数(RGB)值(而不是其名称)创建Color对象,因此Color结构不会将其识别为命名颜色。

This information is not dynamically determined at runtime by iterating through a map containing all of the known colors and their RGB values, but rather stored in private sentinel fields at the time that the Color object is created. 在运行时,不会通过遍历包含所有已知颜色及其RGB值的映射来动态确定此信息,而是在创建Color对象时将其存储在私有标记字段中。 You are losing that information in the process of serializing the color information to your database as an integer. 在将颜色信息作为整数序列化到数据库的过程中,您正在丢失该信息。

You mixed up known colors and just colors. 您混合了已知的颜色和只是颜色。 When you convert a known color to int, and convert it back to color you lose the name. 当您将已知颜色转换为int并将其转换回颜色时,您会失去名称。 You have to do this: 您必须这样做:

 int icolor = System.Drawing.Color.Red.ToArgb();

 Color knownColor = System.Drawing.Color.FromArgb(icolor).ToKnownColor();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM