Copy a diagram to a new one

I want to copy a diagram to an off-screen diagram that I can modify without the user seeing the changes before saving it to an image. I would have thought atDiagram2.Assign(AtDiagram1); would do this, the description for it in atDiagram.pas is: Assign method copies the content of the Source diagram to the current diagram. All objects and properties are copied. which seems to cover what I want. But in practice I can't get it to work. Am I missing something? This is the (simple test) code I used:

procedure TForm1.Button1Click(Sender: TObject);
var
  i : integer;
  blk : TDiagramBlock;
begin
  for i := 0 to 9 do
    begin
    blk := TDiagramBlock.Create(Self);
    blk.Diagram := Form1.atDiagram1;
    blk.Left := i * 20;
    blk.Top := i * 20;
    end;
  atDiagram1.Invalidate;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  atDiagram2.Assign(AtDiagram1);
  atDiagram2.Invalidate;
  Label1.Caption := format('Blockcount from: %d Blockcount to: %d',[atDiagram1.BlockCount,atDiagram2.BlockCount]);
end;

Indeed, Assign only copies the diagram properties, not the objects it contains.
What you can do is use SaveToStream and then LoadFromStream:

  MS := TMemoryStream.Create;
  try
    atDiagram1.SaveToStream(MS);
    MS.Position := 0;
    atDiagram2.LoadFromStream(MS);
  finally
    MS.Free;
  end;

However, note that if both diagrams are owned by the same component, you will have problems with the component names (duplication). In this case you should rename the components before loading them:

  MS := TMemoryStream.Create;
  try
    atDiagram1.SaveToStream(MS);
    for I := 0 to atDiagram1.DControlCount - 1 do
      if atDiagram1.DControls[I].Name <> '' then
        atDiagram1.DControls[I].Name := atDiagram1.DControls[I].Name + '_';

    MS.Position := 0;
    atDiagram2.LoadFromStream(MS);
  finally
    MS.Free;
  end;

Thanks, I think I can make that work, though it will be a lot of renaming of blocks to get the primary diagram back to it's 'proper' names and the secondary diagram with temporary names!

1 Like

This topic was automatically closed 60 minutes after the last reply. New replies are no longer allowed.