【问题标题】:Drawing 2d Matrix on a Winform Component C#在 Winform 组件 C# 上绘制二维矩阵
【发布时间】:2014-03-15 14:10:34
【问题描述】:

我想在一个 winform 项目上绘制一个二维布尔数组。我想在 f[i,j]==1 处放置一个填充矩形,在 f[i,j]==0 处留空。

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

如果有人能给我一个在 winform 组件上绘制二维数组的简单示例,我也将不胜感激,这样我可以更好地理解它,谢谢

【问题讨论】:

  • 您能不能展示一下,到目前为止您尝试了什么?一些基本的代码示例将有助于更好地理解您的问题。

标签: c# arrays winforms drawing


【解决方案1】:

试试这个:

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 *
{
    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);
                        }
                    }
                }
            }
        }
    }
}

【讨论】:

  • 感谢您的努力,感谢。
  • 很高兴能帮上忙。绘图代码应放在 Paint 事件处理程序中,以便在重绘窗口时不会“擦除”矩形。代码已更新。