在Winform组件上绘制2d矩阵C#

时间:2014-03-15 14:10:35

标签: c# arrays winforms drawing

我想在winform项目上绘制一个2维布尔数组。我想把一个填充的矩形放在f [i,j] == 1并留空,其中f [i,j] == 0。

我的第一个问题是,我使用的是winform而且我不太了解我可以在哪个组件上执行此操作。我目前正尝试在面板上进行此操作但到目前为止,我不是很成功。

我还要感谢,如果有人能给我一个在winform组件上绘制二维数组的复杂样本,那么我可以更好地理解它,谢谢

1 个答案:

答案 0 :(得分:0)

试试这个:

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 Stackoverflow
{
    public partial class Print2DArrayForm : Form
    {
        public Print2DArrayForm()
        {
            InitializeComponent();
            //initial the matrix here
            matrix[0, 1] = true;
            matrix[1, 2] = true;
            matrix[1, 1] = true;
            matrix[1, 3] = true;
            matrix[2, 2] = true;
            this.Paint += Draw2DArray;
        }

        bool[,] matrix = new bool[3, 4];

        private void Draw2DArray(object sender, PaintEventArgs e)
        {
            int step = 50; //distance between the rows and columns
            int width = 40; //the width of the rectangle
            int height = 40; //the height of the rectangle

            using (Graphics g = this.CreateGraphics())
            {
                g.Clear(SystemColors.Control); //Clear the draw area
                using (Pen pen = new Pen(Color.Red, 2))
                {
                    int rows = matrix.GetUpperBound(0) + 1 - matrix.GetLowerBound(0); // = 3, this value is not used
                    int columns = matrix.GetUpperBound(1) + 1 - matrix.GetLowerBound(1); // = 4

                    for (int index = 0; index < matrix.Length; index++)
                    {
                        int i = index / columns;
                        int j = index % columns;
                        if (matrix[i, j]) 
                        {
                            Rectangle rect = new Rectangle(new Point(5 + step * j, 5 + step * i), new Size(width, height));
                            g.DrawRectangle(pen, rect);
                            g.FillRectangle(System.Drawing.Brushes.Red, rect);
                        }
                    }
                }
            }
        }
    }
}