我需要在TPanel上绘制图形,最好是直接绘制,这样就不会有其他组件覆盖它,阻碍鼠标事件的捕获(我想在其上绘制一个小的“大小调整手柄”)。我该如何做到这一点?
我需要在TPanel上绘制图形,最好是直接绘制,这样就不会有其他组件覆盖它,阻碍鼠标事件的捕获(我想在其上绘制一个小的“大小调整手柄”)。我该如何做到这一点?
要做到真正正确,你应该编写一个子类。覆盖Paint
方法以绘制大小调整柄,并覆盖MouseDown
、MouseUp
和MouseMove
方法以添加调整大小功能到控件中。
我认为这比尝试在应用程序代码中画一个TPanel
更好,原因如下:
TPanel
中的Canvas
属性是受保护的,因此您无法从类外访问它。您可以通过类型转换来绕过它,但那是作弊。这里有一些开始的东西:
type
TSizablePanel = class(TPanel)
private
FDragOrigin: TPoint;
FSizeRect: TRect;
protected
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
end;
procedure TSizeablePanel.Paint;
begin
inherited;
// Draw a sizing grip on the Canvas property
// There's a size-grip glyph in the Marlett font,
// so try the Canvas.TextOut method in combination
// with the Canvas.Font property.
end;
procedure TSizeablePanel.MouseDown;
begin
if (Button = mbLeft) and (Shift = [])
and PtInRect(FSizeRect, Point(X, Y)) then begin
FDragOrigin := Point(X, Y);
// Need to capture mouse events even if the mouse
// leaves the control. See also: ReleaseCapture.
SetCapture(Handle);
end else inherited;
end;
最简单的方法就是在面板上放置一个TImage。但如果你真的不想这样做,可以在代码编辑器中键入TCanvas,然后按F1键,享受学习它如何在幕后工作的乐趣。(别说我没警告过你...)