简体   繁体   中英

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. 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(?). 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 . So whenever you use its object you get a null reference exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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