.NET中利用反射功能遍历系统预定义的画刷和颜色
昨天晚上在做GDI+的一个图形程序,想试试系统中的哪个预定义颜色比较适合作为人脸的颜色,
结果犹豫了半天没选好。如果做个小程序直接把各种预定义的颜色一行一行展示出来那不就方便了!
后面参考了一篇关于反射的文章,感觉利用反射可以达到我们的目标。
参考的是这篇文章:
http://download.csdn.net/source/1184896 (第02个小程序:遍历画笔(FlipThroughTheBrushes.cs))
程序比较短小,就是利用Brushes这个类型做反射,遍历里面的所有的域,然后一行一行画在我们的主窗口上。
下面是整个小程序。(做的过程中试了下用VS2005的命令行程序做编译,然后用EditPlus码代码,感觉这样挺能练习对语言的熟练度的,呵呵)
代码
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
namespace ShowColor
{
struct BrushWithName
{
public Brush Value;
public String Name;
}
public class ShowColor : Form
{
public static void Main(string[] args)
{
Application.Run(new ShowColor());
}
public ShowColor()
{
this.Text = "ShowColor程序";
this.ClientSize = new Size(800, 600);
this.Paint += new PaintEventHandler(this.PaintForm);
this.SizeChanged += new EventHandler(this.RefreshForm);
}
private void RefreshForm(object sender, EventArgs e)
{
this.Invalidate();
}
private void PaintForm(object sender, PaintEventArgs e)
{
PropertyInfo[] props;
props = typeof(Brushes).GetProperties();
const int numGroup = 4;
BrushWithName[][] brushGroups = new BrushWithName[numGroup][];
int brushCount = 0;
int brushEachGroup = props.Length / numGroup;
for (int i = 0; i < numGroup; ++i)
{
BrushWithName[] brushSubGroup;
brushSubGroup = new BrushWithName[brushEachGroup];
for (int j = 0; j < brushSubGroup.Length && brushCount < props.Length; ++j, ++brushCount)
{
brushSubGroup[j].Value = (Brush)props[brushCount].GetValue(null, null);
brushSubGroup[j].Name = props[brushCount].Name;
}
brushGroups[i] = brushSubGroup;
}
Size clientSize = this.Size;
Size blockSize = new Size(clientSize.Width / numGroup, clientSize.Height / brushEachGroup);
Point location = new Point();
for (int i = 0; i < brushGroups.Length; ++i)
{
for (int j = 0; j < brushGroups[i].Length; ++j)
{
Graphics g = e.Graphics;
if (brushGroups[i][j].Value == null) continue;
g.FillRectangle(brushGroups[i][j].Value, new Rectangle(location, blockSize));
if (blockSize.Height > 10)
{
Font font = new Font("宋体", 10);
string output = brushGroups[i][j].Name;
g.DrawString(output, font, Brushes.Black, location);
}
location.Offset(0, blockSize.Height);
}
location = new Point(location.X + blockSize.Width, 0);
}
}
}
}
这里主要都是做GDI+的画图。我特意用了下二级数组,因为以前我做类似的任务都喜欢用List泛型,感觉还是要多熟练下多维数组的用法。
不过List泛型里的ForEach方法我还是觉得蛮过瘾,因为用匿名委托感觉就像是在做函数式编程~
下面是程序的输出画面~在各种平台里运行这东西应该显示效果都不会差太远吧~