패널에 사각형을 그릴 수있는 작은 프로그램이 있습니다. 그러나 그려진 후에는 나중에 표시 할 List 배열에 저장하고 싶습니다. MouseButtonUp 이벤트에서 전달하려고했지만 마우스가 처음에 Up 상태에 있고 따라서 문제 (?)로 생각할 때 Null 참조 예외를 반환합니다. 그려진 모양을 저장할 수있는 방법이 있습니까?배열에 그려진 사각형을 저장하는 방법은 무엇입니까?
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'를 초기화하지 않습니다. – Abion47
가능한 복제본 [NullReferenceException은 무엇이며 어떻게 수정합니까?] (http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it)) –