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

时间:2016-10-25 17:29:00

标签: c# winforms windows-forms-designer

我有一个小程序,我可以在Panel上绘制一个矩形。但是,在绘制之后,我想将它存储在List数组中以供稍后显示。我试图在MouseButtonUp事件中传递它,但它返回Null Reference Exception,因为我认为鼠标最初处于Up状态,因此问题(?)。有没有办法实现存储绘制的形状?

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




}
}

2 个答案:

答案 0 :(得分:3)

您需要初始化private List<Rectangle> _rectangleList = new List<Rectangle>();

{{1}}

答案 1 :(得分:2)

您尚未初始化_rectangleList。因此,无论何时使用其对象,都会得到一个空引用异常。