在写这篇“GDI+与WPF中的颜色简析”之前,我试着使用GDI+生成KnownColor列表。现将关键代码贴出来吧。
最终效果图:
现将关键代码:
Bitmap m_Bitmap = null;
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (m_Bitmap != null)
{
Graphics g = e.Graphics;
g.DrawImage(m_Bitmap, new Point(0, 0));
}
}
private void btnTestColor_Click(object sender, EventArgs e)
{
int count = 0;
foreach (string s in Enum.GetNames(typeof(KnownColor)))
{
count++;
}
int cols = 4;
int rows = count / cols;
if (count % rows > 0) rows++;
int rectWidth = 100;
int rectHeight = 30;
int wordSpaceFromRect = 10;
int rowSpace = 10;
int marginTop = 20;
int marginBottom = 20;
int width = 300 * cols + 50;
int height = (rectHeight + rowSpace) * rows + marginTop + marginBottom ;
m_Bitmap = new Bitmap(width, height);
Graphics g = Graphics.FromImage(m_Bitmap);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
g.Clear(Color.White);
Color someColor = Color.FromArgb(0);
Color redShade = Color.FromArgb(255, 200, 0, 100);
SolidBrush myBrush1;
Font myFont = new Font("Arial", 12);
int x = 20;
int y = marginTop;
for (int i = 0; i < count; i++ )
{
someColor = Color.FromKnownColor((KnownColor)i);
myBrush1.Color = someColor;
g.FillRectangle(myBrush1, x, y, rectWidth, rectHeight);
g.DrawRectangle(Pens.Black, x, y, rectWidth, rectHeight);
g.DrawString(someColor.ToString().Replace("Color [","").Replace("]",""), myFont, Brushes.Black, x + rectWidth + wordSpaceFromRect, y);
if (i % cols == cols - 1)
{
y += rectHeight + rowSpace;
x -= 300 * (cols - 1);
}
if (i % cols < cols - 1)
{
x += 300;
}
}
g.Dispose();
this.Invalidate();
}