freepascallazarus

How can I hide the black background canvas of a TImage?


I would like draw blue lines onto a TImage, which is a child object of a ScrollBox. But when I drawing, it always shows the black background canvas rectangle under the blue lines. I would like see only the lines without the black background rectangle. Can I do a transparent TImage from it?

I tried with this code so far, but it's only partially good:

procedure TForm1.gridButtonMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var bm: TBitmap;
  hlines,vlines: word;
begin
  if showgrid=true then
  begin
     showgrid:=false;
     if gridon=true then
     begin
       FreeAndNil(gridimage);
       gridon:=false;
     end;
  end
  else
  begin
    showgrid:=true;
    if gridon=false then
    begin
      gridimage:=TImage.Create(terrainScrBox);
      gridimage.Parent:=terrainScrBox;
      gridimage.Left:=0;
      gridimage.Top:=0;
      gridimage.width:=terrainCanvas.width; //terrainCanvas is a TImage component.
      gridimage.height:=terrainCanvas.Height;
      griddrawing(gridimage);
    end;
    gridon:=true;
  end;
end;
 
procedure TForm1.griddrawing(Sender: TObject);
var hlines,vlines: word;
begin
     vlines:=tilewidth;
     hlines:=tileheight;
     //with gridimage do // If these lines are commented, the grid is visible without black rectangle,
     //begin // but not at gridimage, but at TForm1, and I can't switch off it.
       canvas.pen.color:=clBlue;
       while vlines<width do
       begin
          canvas.line(vlines,0,vlines,height);
          inc(vlines,tilewidth);
       end;
       while hlines<height do
       begin
          canvas.line(0,hlines,width,hlines);
          inc(hlines,tileheight);
       end;
     //end;
end;

Solution

  • The TImage control is not truly transparent. But I guess that that is not really what you want, but instead that you could define the background color or maybe even a picture that would appear to be behind whatever you want to draw in front of that background.

    The default color of the TImage is black, which is why you see the image (after drawing the lines) as blue lines on a black background.

    To change the background color you should, after you have created the gridimage, but just before you call griddrawing, fill the image with the color you want to have as background, e.g.:

      with gridimage do begin
        Brush.Color := clWhite;
        Canvas.FillRect(0, 0, Width, Height);
      end;
    

    I did not fully understand what role the terrainCanvas plays in your setup, but if that should be visible behind the blue lines, then draw that terrainCanvas on the gridImage instead of the FillRect above (before drawing the blue lines).