我试图通过在单击时拖动鼠标来创建一个正方形,我可以单独创建正方形,但无法使其与预览一起使用。拖动时,预览形状由于某种原因不会被删除,我不太明白为什么会发生这种情况。我将包含发生这种情况的图片和视频,因为很难用文字解释它。
预览如何工作:有 2 支笔,一支用于擦除正在创建的形状,同时光标在表单中移动,直到松开并设计出正方形
public partial class Form1 : Form
{
Pen pen, eraser;
Graphics graphics;
Bitmap bitmap;
Point startPoint, endPoint;
int choice;
Boolean draw;
int width;
int height;
public Form1()
{
InitializeComponent();
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (draw && choice == 1)
{
width = e.Location.X - startPoint.X;
height = e.Location.Y - startPoint.Y;
width = height;
Rectangle shape = new Rectangle(startPoint.X, startPoint.Y, width, height);
graphics.DrawRectangle(pen, shape);
pictureBox1.Refresh();
draw = false;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (draw && choice == 1)
{
width = e.Location.X - startPoint.X;
height = e.Location.Y - startPoint.Y;
width = height;
graphics.DrawRectangle(eraser, startPoint.X, startPoint.Y, width, height);
graphics.DrawRectangle(pen, startPoint.X, startPoint.Y, width, height);
pictureBox1.Refresh();
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
startPoint = e.Location;
draw = true;
}
您的问题可能与您的想法相反。您之前绘制的任何正方形都应该自动擦除,直到您需要将其保存在某种文档中(请参见下面的
Squares
),以便将多个形状放在一起。
class PictureBoxEx : PictureBox
{
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
_mouseDownPoint = e.Location;
}
Point _mouseDownPoint = default;
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
_mouseCurrentPoint = e.Location;
if (MouseButtons == MouseButtons.Left)
{
BeginInvoke((MethodInvoker)delegate { Invalidate(); });
}
}
Point _mouseCurrentPoint = default;
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
Squares.Add(_currentSquare);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if(MouseButtons == MouseButtons.Left)
{
var delta = _mouseCurrentPoint.Y - _mouseDownPoint.Y;
using (var pen = new Pen(Color.DarkRed, 2F))
{
Debug.WriteLine($"{_mouseDownPoint}{_mouseCurrentPoint}");
var width = _mouseCurrentPoint.X - _mouseDownPoint.X;
var height = _mouseCurrentPoint.Y - _mouseDownPoint.Y;
var side = Math.Max(width, height);
_currentSquare = new Rectangle(_mouseDownPoint, new Size(side, side));
e.Graphics.DrawRectangle(pen, _currentSquare);
// Comment this out to keep just the current square.
foreach (var square in Squares)
{
e.Graphics.DrawRectangle(pen, square);
}
}
}
}
Rectangle _currentSquare = default;
List<Rectangle> Squares { get; } = new List<Rectangle>();
}