如何在TPanel上绘图

Jam*_*amo 3 delphi components canvas tpanel

我需要在TPanel上绘制,理想情况下是直接的,所以我没有其他组件可以阻止鼠标事件陷阱(我想在它上面画一点"尺寸 - 抓握").我应该怎么做呢?

Rob*_*edy 10

要真正做到对,你应该写一个后代类.重写Paint绘制大小调整手柄,和覆盖的方法MouseDown,MouseUpMouseMove方法来添加调整大小功能控制.

我认为这比尝试TPanel在应用程序代码中绘制一个更好的解决方案有几个原因:

  1. Canvas物业受到保护TPanel,因此您无法从课外进入.你可以用类型转换来解决这个问题,但这是作弊行为.
  2. "可恢复性"听起来更像是面板的一个功能,而不是应用程序的一个功能,因此将其放在面板控件的代码中,而不是应用程序的主代码中.

这是让你入门的东西:

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;
Run Code Online (Sandbox Code Playgroud)


Arg*_*tyr 7

这是Raize Components可以让您的生活更轻松的众多方式之一.我只是进入Delphi,放在TRzPanel上,然后输入:

RzPanel1.Canvas.Rectangle ...

我确信还有其他解决方案 - 但我不必用Raize来寻找它们.

(只是满意的客户大约10年......)

编辑:鉴于你的目标,以及你已经拥有Raize Components的声明,我还应该指出TRzSizePanel处理面板的调整大小和OnCanResize等有用的事件(以确定是否允许调整大小到特定的新宽度或高度) .