餵你感到沉淪,Web顏色列表中的C#應用程序
舉例來說,如果我使用Visual Studio設置在winform面板的背景色,我可以從3所列出拿起顏色:
定製,網絡,系統
是否有可能僅檢索我的C#代碼應用程序中的Web顏色?他們是KnownColor的一部分,但到目前爲止,我只能找到如何從我的列表中消除系統控制。
我想使用Web顏色,因爲它們以很好的方式排序,我想將它們插入到自我實現的組合框中。
謝謝
餵你感到沉淪,Web顏色列表中的C#應用程序
舉例來說,如果我使用Visual Studio設置在winform面板的背景色,我可以從3所列出拿起顏色:
定製,網絡,系統
是否有可能僅檢索我的C#代碼應用程序中的Web顏色?他們是KnownColor的一部分,但到目前爲止,我只能找到如何從我的列表中消除系統控制。
我想使用Web顏色,因爲它們以很好的方式排序,我想將它們插入到自我實現的組合框中。
謝謝
Color
結構包含了所有的網頁顏色爲常數(系統顏色在SystemColors
類中定義爲常量)
要獲得這些顏色的列表只是做:
var webColors = GetConstants(typeof(Color));
var sysColors = GetConstants(typeof(SystemColors));
具有GetConstants
定義如下:
static List<Color> GetConstants(Type enumType)
{
MethodAttributes attributes = MethodAttributes.Static | MethodAttributes.Public;
PropertyInfo[] properties = enumType.GetProperties();
List<Color> list = new List<Color>();
for (int i = 0; i < properties.Length; i++)
{
PropertyInfo info = properties[i];
if (info.PropertyType == typeof(Color))
{
MethodInfo getMethod = info.GetGetMethod();
if ((getMethod != null) && ((getMethod.Attributes & attributes) == attributes))
{
object[] index = null;
list.Add((Color)info.GetValue(null, index));
}
}
}
return list;
}
編輯:
爲了獲得顏色分類酷似VS做:
var webColors = GetConstants(typeof(Color));
var sysColors = GetConstants(typeof(SystemColors));
webColors.Sort(new StandardColorComparer());
sysColors.Sort(new SystemColorComparer());
與StandardColorComparer
和SystemColorComparer
定義如下:
class StandardColorComparer : IComparer<Color>
{
// Methods
public int Compare(Color color, Color color2)
{
if (color.A < color2.A)
{
return -1;
}
if (color.A > color2.A)
{
return 1;
}
if (color.GetHue() < color2.GetHue())
{
return -1;
}
if (color.GetHue() > color2.GetHue())
{
return 1;
}
if (color.GetSaturation() < color2.GetSaturation())
{
return -1;
}
if (color.GetSaturation() > color2.GetSaturation())
{
return 1;
}
if (color.GetBrightness() < color2.GetBrightness())
{
return -1;
}
if (color.GetBrightness() > color2.GetBrightness())
{
return 1;
}
return 0;
}
}
class SystemColorComparer : IComparer<Color>
{
// Methods
public int Compare(Color color, Color color2)
{
return string.Compare(color.Name, color2.Name, false, CultureInfo.InvariantCulture);
}
}
注: :
此代碼已經從System.Drawing.Design.ColorEditor
通過反射器。
var webColors =
Enum.GetValues(typeof(KnownColor))
.Cast<KnownColor>()
.Where (k => k >= KnownColor.Transparent && k < KnownColor.ButtonFace) //Exclude system colors
.Select(k => Color.FromKnownColor(k));
編輯:
要訂購的顏色追加:
.OrderBy(c => c.GetHue())
.ThenBy(c => c.GetSaturation())
.ThenBy(c => c.GetBrightness());
比其他答案更簡潔。 – 2013-02-12 04:52:44
如果你需要它的原色進行排序,你可以使用它作爲起點:
var colors = Enum.GetValues(typeof(KnownColor))
.Cast<KnownColor>()
.Select(kc => Color.FromKnownColor(kc))
.OrderBy(c => c.GetHue())
你想知道KnownColor枚舉的列表? –
Magnus
2011-02-23 13:38:34
基本上是的,但我想要在Visual Studio中的Web選項卡中對顏色進行排序。 我試圖用一些算法對顏色進行排序,但結果並不理想。 – Klaus78 2011-02-23 14:14:17