Use Reflection To Generate Complete Color Chart






4.20/5 (2 votes)
Apr 16, 2002
2 min read

82654

822
Artcile on use of reflection to get color values to draw the complete color chart
Introduction
In GDI+, for drawing any item we need to pick up a color for either creating
a brush or a pen. .NET framework has provided System.Drawing.Color
structure which contains 141 colors. That makes life pretty easy. But
there are some developers like me who have hard time corelating the color names
with what actually they look like.
To solve this probelm, we decided to come up with a chart that will display
all the colors along with the names used in Color
structure. The
crude approach could have been that we use a huge switch
statement
with each case
representing the colors defined in the structure.
But there is a very nice approach that we took. .NET framework procides a
very powerful feature called Reflection. All the colors in
System.Drawing.Color
structure are declared as public
static
properties. So the idea is pretty simple.
- Get
Type
ofSystem.Drawing.Color
strcuture. - Call
GetProperties
method onType
instance. Make sure that you use the appropriateBindingFlags
attribute to get only the properties that are of interest. In our case we are only interested inpublic static
properties. Therefore we will useBindingFlags.Public
,BindingFlags.Static
andBindingFlags.DeclaredOnly
ORed together. The purpose of specifyingBindingFlags.DeclaredOnly
attribute is to get only thestatic
properties that are declared only in this class only. We are not interested in properties of any parent class or structure. - Iterate through each item in
PropertyInfo
array value returned byGetProperties
method. CallName
property onPropertyInfo
object to get the name of each color. And callGetValue
method to get the actual value ofColor
. - Rest is just implementation detail and book keeping on how to arrange all the colors on the bitmap and display it as a chart.
The complete code is attached with the article. Take a look at it for details.
Color testColor = Color.AliceBlue;
Type colorType = testColor.GetType();
if (null != colorType)
{
PropertyInfo[] propInfoList =
colorType.GetProperties(BindingFlags.Static|BindingFlags.DeclaredOnly
|BindingFlags.Public);
int nNumProps = propInfoList.Length;
for (int i = 0; i < nNumRows; i++)
{
PropertyInfo propInfo = (PropertyInfo)propInfoList[nIdx];
Color color = (Color)propInfo.GetValue(null, null);
string strColorName = propInfo.Name;
}
}
The complete color chart is available at our web site at Complete Color Chart.