Search code examples
lazarus

Canvas line disappearing


Let's say i draw a green rectangle with TPaintBox on a panel(FillRect method). On this rectangle I make horizontal lines(lineTo method). Then on those lines I put TShape(e.g a square). Now when I change the visibility of the TShape to false part of the line in which there was previously the TShape disappears leaving me with the effect like this:

enter image description here

How do I do that this part of the line doesn't disappear?

Here's the code + I noticed an odd thing while I was writing this code: if I do not put the showMessage method in the code the line and the tShape will not display. Why is that?

var
    Panel1 : TPanel;
    PaintBox1 : TPaintBox;

procedure TForm1.Button1Click(Sender: TObject);
var t : TShape;

begin

    Panel1 := TPanel.Create(form1);
    Panel1.parent := form1;
    Panel1.Color := clGreen;
    Panel1.Width := 500;
    Panel1.Height := 500;
    Panel1.Top := 0;
    Panel1.Left := 0;

    PaintBox1 := TPaintBox.Create(form1);
    PaintBox1.parent := Panel1;
    PaintBox1.Width := 500;
    PaintBox1.Height := 500;
    PaintBox1.Top := 0;
    PaintBox1.Left := 0;
    //showMessage('eee');
    PaintBox1.Canvas.Pen.Color := clWhite;
    PaintBox1.Canvas.line(0,50,PaintBox1.Width,50);

    t := TShape.Create(form1);
    t.parent := Panel1;
    t.Brush.Color := clRed;
    t.Width := 50;
    t.Height := 50;
    t.Top := 25;
    t.Left := 200;
    t.Visible :=false;
end;

Solution

  • The problem you have is because you are painting at the wrong point in your program. Painting to a paint box control must happen in the OnPaint event handler. The content of a paint box is re-painted on demand. The system does this when it needs to by firing the OnPaint event. You need to move the painting code into such an event handler.

    If you wish to draw to a persistent canvas then you could consider using a TImage instead.