You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Delphi 2010:如何保存叠加TPaintBox绘制内容的TImage?

合并TImage与TPaintBox画布保存合成图的两种方法

方法一:直接合成画布(推荐,适配当前场景)

既然TImage和TPaintBox尺寸完全一致,没必要额外记录绘制命令,直接创建新位图合并两者内容即可,步骤如下:

  1. 创建与目标控件同尺寸的TBitmap对象
  2. 先将TImage的背景图绘制到新位图上
  3. 再把TPaintBox当前的画布内容复制到新位图对应位置
  4. 保存合成后的位图

Delphi代码示例:

procedure SaveCombinedImage(Image: TImage; PaintBox: TPaintBox; const FileName: string);
var
  CombinedBmp: TBitmap;
begin
  CombinedBmp := TBitmap.Create;
  try
    // 匹配控件尺寸
    CombinedBmp.Width := Image.Width;
    CombinedBmp.Height := Image.Height;
    // 绘制背景图
    CombinedBmp.Canvas.Draw(0, 0, Image.Picture.Bitmap);
    // 叠加PaintBox上的折线
    CombinedBmp.Canvas.CopyRect(
      Rect(0, 0, PaintBox.Width, PaintBox.Height),
      PaintBox.Canvas,
      Rect(0, 0, PaintBox.Width, PaintBox.Height)
    );
    // 保存文件
    CombinedBmp.SaveToFile(FileName);
  finally
    CombinedBmp.Free;
  end;
end;

这种方法完全基于当前控件的显示状态,无需维护绘制历史,代码简单高效,刚好满足你“保存当前屏幕显示内容”的需求。

方法二:重放绘制命令(适合需后续编辑的场景)

如果之后需要重新打开文件继续编辑折线,就得提前记录所有绘制操作(比如把每条折线的坐标点存入列表),保存时再将这些命令重放到新位图上:

  1. 提前维护存储折线点的列表(比如TList<TPointArray>),用户每次绘制折线时就把点存入列表
  2. 保存时先复制TImage的背景到新位图
  3. 遍历列表,用相同的画笔参数重绘所有折线
  4. 保存合成后的位图

Delphi代码示例:

// 假设窗体类中已声明:LinePoints: TList<TPointArray>;

procedure SaveByReplayingCommands(Image: TImage; const LinePoints: TList<TPointArray>; const FileName: string);
var
  CombinedBmp: TBitmap;
  i: Integer;
begin
  CombinedBmp := TBitmap.Create;
  try
    CombinedBmp.Width := Image.Width;
    CombinedBmp.Height := Image.Height;
    // 绘制背景
    CombinedBmp.Canvas.Draw(0, 0, Image.Picture.Bitmap);
    // 重放绘制命令(注意匹配之前的画笔设置)
    CombinedBmp.Canvas.Pen.Color := clRed;
    CombinedBmp.Canvas.Pen.Width := 2;
    for i := 0 to LinePoints.Count - 1 do
    begin
      CombinedBmp.Canvas.Polyline(LinePoints[i]);
    end;
    // 保存文件
    CombinedBmp.SaveToFile(FileName);
  finally
    CombinedBmp.Free;
  end;
end;

这种方法需要额外管理绘制历史,但好处是保存的内容保留了可编辑性,后续可修改折线。

总结

  • 仅需保存当前显示效果:选方法一,省事高效
  • 需要后续编辑折线:选方法二,提前记录绘制命令

内容的提问来源于stack exchange,提问作者ChrisH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 00:33:21