1
我有一個小程序,我可以在面板上畫一個矩形。但是,繪製後,我想將它存儲在List數組中以供稍後顯示。我試圖只在MouseButtonUp事件中傳遞它,但它返回空引用異常,因爲我認爲鼠標最初處於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);
}
}
}
}
你永遠不會初始化'_rectangleList'。 – Abion47
可能重複[什麼是NullReferenceException,以及如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it ) –