Search code examples
delphicanvasdelphi-2010shapes

Delphi 2010 - How to Copy and Clear the TShape


Ok, after working with TShape, I need to clean my "Shape1" from Lines and Text.

And also how to copy everything in "Shape1" into "Shape2" ?

Thanks B4 ^o^

    type
      TShape = class(ExtCtrls.TShape); //interposer class

      TForm1 = class(TForm)
        Shape1: TShape;
        Shape2: TShape;
        Button1: TButton;
        Button2: TButton;
        procedure Button1Click(Sender: TObject);
        procedure Button2Click(Sender: TObject);
      private
      public
      end;

    var
      Form1: TForm1;

    implementation

    {$R *.dfm}

    procedure TForm1.Button1Click(Sender: TObject);
    begin
//        Draw some text on Shape1 := TShape 
        Shape1.Canvas.Font.Name :='Arial';// set the font 
        Shape1.Canvas.Font.Size  :=20;//set the size of the font
        Shape1.Canvas.Font.Color:=clBlue;//set the color of the text
        Shape1.Canvas.TextOut(10,10,'1999');
    end;

    procedure TForm1.Button2Click(Sender: TObject);
    begin
//        Copy everything from Shape1 to Shape2 (make a duplication)
//        How to do it ? 
        showmessage('copy Shape1 into Shape2');    
    end;

    End.

Solution

  • Following pseudo-code makes a copy of SourceShape canvas content to the TargetShape canvas, but only until the TargetShape is refreshed:

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      TargetShape.Canvas.CopyRect(Rect(0, 0, TargetShape.ClientWidth,
        TargetShape.ClientHeight), SourceShape.Canvas, Rect(0, 0,
        SourceShape.ClientWidth, SourceShape.ClientHeight));
    end;
    

    To clear the previously copied content, you can use the following:

    procedure TForm1.Button2Click(Sender: TObject);
    begin
      TargetShape.Invalidate;
    end;
    

    To keep your drawing persistent you need to implement your own OnPaint event, in which whenever it fires, copy the current canvas content from the source to target using the CopyRect method like shown above.

    But the question is then, why to use a TShape control at all. It would be better to use TPaintBox and draw your stuff by yourself including the shapes that are drawn by TShape control.