您不能删除绘图,您必须在其上绘制其他内容。
在您显示的代码中,您可以简单地设置FSelection
为一个空的 0x0 矩形,Invalidate()
然后PaintBox
再次设置。它的正常图片将被绘制,您不会在其上绘制矩形。
procedure TForm1.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
FSelection := Rect(X, Y, X, Y);
FSelecting := True;
end;
end;
procedure TForm1.PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if FSelecting then
begin
FSelection.Right := X;
FSelection.Bottom := Y;
PaintBox1.Invalidate;
end;
end;
procedure TForm1.PaintBox1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if (Button = mbLeft) and FSelecting then
begin
FSelecting := False;
FSelection := Rect(0, 0, 0, 0);
PaintBox1.Invalidate;
end;
end;
procedure TForm1.PaintBox1Paint(Sender: TObject);
begin
//...
PaintBox1.Canvas.Brush.Color := clRed;
PaintBox1.Canvas.Rectangle(FSelection);
end;
或者,假设您需要记住选定的矩形以用于其他事物,那么就不要将选定的矩形绘制到PaintBox
whenFSelecting
为 false 上。
procedure TForm1.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
FSelection := Rect(X, Y, X, Y);
FSelecting := True;
end;
end;
procedure TForm1.PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if FSelecting then
begin
FSelection.Right := X;
FSelection.Bottom := Y;
PaintBox1.Invalidate;
end;
end;
procedure TForm1.PaintBox1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if (Button = mbLeft) and FSelecting then
begin
FSelecting := False;
PaintBox1.Invalidate;
end;
end;
procedure TForm1.PaintBox1Paint(Sender: TObject);
begin
//...
if FSelecting then
begin
PaintBox1.Canvas.Brush.Color := clRed;
PaintBox1.Canvas.Rectangle(FSelection);
end;
end;
无论哪种方式,为了更好地衡量,您应该用虚线边框绘制透明的矩形,以便用户可以看到他们正在选择的内容而不会太打扰:
procedure TForm1.PaintBox1Paint(Sender: TObject);
begin
//...
if FSelecting then
begin
PaintBox1.Canvas.Brush.Style := bsClear;
PaintBox1.Canvas.Pen.Style := psDot;
PaintBox1.Canvas.Rectangle(FSelection);
end;
end;