简体   繁体   English

如何将绘制的矩形存储在数组中?

[英]How to store a drawn rectangle in an array?

I have a small program where I can draw a rectangle on a Panel. 我有一个小程序,可以在面板上绘制矩形。 However, after it is drawn, I'd like to store it in a List array for later display. 但是,绘制完之后,我想将其存储在List数组中以供以后显示。 I tried to just pass it in a MouseButtonUp event, but it returns Null Reference Exception, as I think mouse is initially in Up state and thus the issue(?). 我试图在MouseButtonUp事件中传递它,但是它返回Null Reference Exception,因为我认为鼠标最初处于Up状态,因此是issue(?)。 Is there any way to achieve storing the drawn shapes? 有什么方法可以存储绘制的形状吗?

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

namespace GraphicEditor
{
public partial class Form1 : Form
{
    private bool _canDraw;
    private int _startX, _startY;
    private Rectangle _rectangle;
    private List<Rectangle> _rectangleList;

    public Form1()
    {
        InitializeComponent();


    private void imagePanelMouseDown(object sender, MouseEventArgs e)
    {
        _canDraw = true;
        _startX = e.X;
        _startY = e.Y;

    }

    private void imagePanelMouseUp(object sender, MouseEventArgs e)
    {
        _canDraw = false;
       // _rectangleList.Add(_rectangle); //exception
    }

    private void imagePanelMouseMove(object sender, MouseEventArgs e)
    {
        if(!_canDraw) return;

        int x = Math.Min(_startX, e.X);
        int y = Math.Max(_startY, e.Y);
        int width = Math.Max(_startX, e.X) - Math.Min(_startX, e.X);
        int height = Math.Max(_startY, e.Y) - Math.Min(_startY, e.Y);
        _rectangle = new Rectangle(x, y, width, height);
        Refresh();
    }

    private void imagePanelPaint(object sender, PaintEventArgs e)
    {
        using (Pen pen = new Pen(Color.Red, 2))
        {
            e.Graphics.DrawRectangle(pen, _rectangle);
        }
    }




}
}

您需要初始化_rectangleList

private List<Rectangle> _rectangleList = new List<Rectangle>();

You have not initialized _rectangleList . 您尚未初始化_rectangleList So whenever you use its object you get a null reference exception. 因此,无论何时使用它的对象,您都会得到一个null引用异常。

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

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