Question

I have subclassed ExtCtrls.TPaintBox with several help functions and overridden the Paint method. I can add a TPaintBox to a form which then acts as my custom paintbox object and draws the desired output.

Now I want to draw (write) the contents of my paintbox to a file, but with different dimensions; e.g. inside the UI of my application the paintbox has size 150x600 (width x height), but when drawing to the file, I need it to be larger.

I want to be able to reuse my drawing code (= TPaintBox.Paint) and virtually draw it to an object and then save that object to a file.

I'm already able to export it, but resizing on export makes the image look like you would enlarge it with paint.

Was it helpful?

Solution

Your paint box OnPaint event handler is probably dedicated to painting to the size of the paint box. You need to generalize the painting code to be able to draw to a general canvas whose size is only known at runtime. That way you can draw to the low resolution paint box and the high resolution file with the same painting code.

Extract the code inside your OnPaint event handler into a separate method that looks like this:

procedure TForm1.DoPaintBoxPaint(Canvas: TCanvas);
begin
  // All painting code goes here. Use Canvas.ClipRect to infer size of canvas.
end;

Then call this method from your OnPaint handler. Pass PaintBox1.Canvas as the parameter to the method.

In outline that looks like this:

procedure TForm1.PaintBox1Paint(Sender: TObject);
begin
  DoPaintBoxPaint(PaintBox1.Canvas);
end;

Finally you can call the method from the method that saves the image to file. In that case I assume you have a temporary bitmap on which to draw the image before saving. Pass the canvas of that bitmap. A sketch of that code would be:

Bitmap := TBitmap.Create;
try
  Bitmap.SetSize(Width, Height);
  DoPaintBoxPaint(Bitmap.Canvas);
  Bitmap.SaveToFile(...);
finally
  Bitmap.Free;
end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top