【问题标题】:Color cells of a matrix with C#使用 C# 矩阵的颜色单元格
【发布时间】:2012-12-08 22:22:13
【问题描述】:

我需要创建一个 40x40 矩阵并手动为每个单元格着色,如下所示。

我认为我可以在表单应用程序上使用 40*40=160 个标签并一一着色,但这不是很有效。对此的最佳做法是什么。也许是 ColorMatrix?

【问题讨论】:

  • 您可以使用 Panel 并编写自己的 Paint 事件处理程序。
  • 您将如何确定哪些颜色属于哪个部分?您是否已经有了这些值的矩阵?
  • @MichaelPerrenoud 我把它们放在 txt 文档中。在这份文件中,我掌握了所有信息。例如:“(12,13)​​--> #FFE699”。我将解析此文档并将这些颜色放在矩阵上。
  • 可以利用像 WriteableBitmapEx (writeablebitmapex.codeplex.com) 这样的库来生成单个图像位图并绘制每个正方形。不确定该项目是否与 WinForms 兼容(但肯定是 WPF)

标签: c# colormatrix


【解决方案1】:

这是一个完整但简单的 Windows 窗体应用程序。

这可能是最直接的方式。考虑一下我没有从矩阵中获取颜色的事实,但是您明白了,它具有您应该在代码中绘制它的方式。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            for (int x = 0, y = 0; x + y != (this.Width + this.Height); x++)
            {
                var color = Color.Red;
                if (x % 2 == 0 && y % 2 != 0) { color = Color.Blue; }

                e.Graphics.FillRectangle(new SolidBrush(color), x, y, 1, 1);

                if (x == this.Width)
                {
                    x = -1;
                    y++;
                }
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    拦截 OnPaint 事件的另一种方法是创建一个 40x40 像素的位图,例如通过 System.Drawing.Bitmap 类,设置所有像素的颜色。

    最后根据您的 UI 技术在 PictureBox(Windows 窗体)或 Image (WPF) 中显示它,并设置缩放值以填充整个控件的大小。

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 2011-10-09
      • 2010-10-21
      • 1970-01-01
      • 2012-11-06
      • 2021-10-23
      相关资源
      最近更新 更多