将画布另存为图像 [英] Save canvas as an image

查看:107
本文介绍了将画布另存为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Delphi XE2编写程序.我在画布上绘制一些线条和形状.我想使用保存对话框将该Canvas保存为图像文件.

I am writing a program using Delphi XE2. I draw some lines and shapes on a Canvas. I want to save that Canvas as an image file using a save dialog.

因此,我在表单上有一个保存按钮,然后单击它会打开保存对话框.我应该如何继续保存画布?

So I have a save button on my form and by clicking it, it opens the save dialog. How should I proceed to be able to save the Canvas?

推荐答案

目前,您很可能在 TPaintBox 或表单本身的 OnPaint 事件中具有代码.该代码可能看起来像这样:

At the moment you most likely have code in an OnPaint event for a TPaintBox or the form itself. That code might look like this:

procedure TMyForm.PaintBox1Paint(Sender: TObject);
begin
  with PaintBox1.Canvas do
  begin
    MoveTo(0, 0);
    LineTo(42, 666);
    // and so on.
  end;
end;

我们需要做一些重构.我们需要将绘画代码提取到单独的方法中.将该方法传递给画布,以便与它所绘制的画布无关.

We need to do a little re-factoring. We need to extract that paint code into a separate method. Pass that method a canvas so that it is agnostic of the canvas on which it draws.

procedure TMyForm.PaintToCanvas(Canvas: TCanvas);
begin
  with Canvas do
  begin
    MoveTo(0, 0);
    LineTo(42, 666);
    // and so on.
  end;
end;

procedure TMyForm.PaintBox1Paint(Sender: TObject);
begin
  PaintToCanvas(PaintBox1.Canvas);
end;

我们现在正好回到了开始的位置,但是已经准备好实现真正的目标.让我们编写一个函数以绘制到位图,然后保存到文件:

We are now back exactly where we started, but ready to strike at the real goal. Let's write a function to paint to a bitmap and then save to a file:

procedure TMyForm.PaintToFile(const FileName: string);
var
  Bitmap: TBitmap;
begin
  Bitmap := TBitmap.Create;
  try
    Bitmap.SetSize(Paintbox1.Width, Paintbox1.Height);
    PaintToCanvas(Bitmap.Canvas);
    Bitmap.SaveToFile(FileName);
  finally
    Bitmap.Free;
  end;
end;

这自然可以扩展到其他图像类型,例如GIF,PNG,JPEG等.

This can naturally be extended to other image types like GIF, PNG, JPEG etc.

这篇关于将画布另存为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆