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

标签 c# winforms windows-forms-designer

我有一个小程序,可以在面板上绘制一个矩形。但是,在绘制之后,我想将它存储在一个 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);
        }
    }




}
}

最佳答案

您需要初始化_rectangleList:

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

关于c# - 如何将绘制的矩形存储在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40246124/

相关文章:

c# - 关联控件 C# 的简便方法

c# - 当 DataSource 是 List<string[]> 时,如何使用 DisplayMember 获取 string[] 的第一个元素?

c# - Outlook 加载项和 Windows 窗体协作

.net - 如何正确标记代码指标的设计器代码以忽略它

c# - 这可以通过使用 linq 使其更具可读性吗?

c# - 在 TPL 上执行长时间任务时图像渲染速度缓慢

C# Excel 百分比转换为小数

c# - 如何关闭当前窗体 Winform C#

c# - VerticalLineAnnotation 未显示在 RangeBar MSChart 上

c# - 如何使用Winform保存类的当前应用程序状态?