繁体   English   中英

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

[英]Drawing 2d Matrix on a Winform Component C#

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

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

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

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM