gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:50:21 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com