如何将Skia4Delphi中TSkPaintBox的画布保存到文件并转为TBitmap?
解决TSkPaintBox签名导出为TBitmap及保存文件的问题
核心前提
要导出签名,你需要先维护一个ISKPath对象记录用户的绘制路径(因为TSkPaintBox的画布是临时的,每次重绘都会刷新,无法直接从其Canvas提取内容)。先在窗体类中声明相关变量:
private FSignaturePath: ISKPath; FIsDrawing: Boolean;
然后在TSkPaintBox的鼠标事件中记录路径,在OnPaint事件中绘制:
procedure TForm1.SkPaintBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then begin FIsDrawing := True; FSignaturePath := TSKPath.Create; FSignaturePath.MoveTo(X, Y); end; end; procedure TForm1.SkPaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if FIsDrawing then FSignaturePath.LineTo(X, Y); SkPaintBox1.Repaint; end; procedure TForm1.SkPaintBox1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then FIsDrawing := False; end; procedure TForm1.SkPaintBox1Paint(Sender: TObject; const ACanvas: ISKCanvas); var LPaint: ISKPaint; begin LPaint := TSKPaint.Create; LPaint.Style := TSKPaintStyle.Stroke; LPaint.Color := TSKColors.Black; LPaint.StrokeWidth := 2; ACanvas.DrawPath(FSignaturePath, LPaint); end;
导出为TBitmap
通过创建与TSkPaintBox尺寸一致的SKBitmap,将保存的签名路径绘制到该Bitmap,再转换为VCL的TBitmap:
function TForm1.SignatureToBitmap: TBitmap; var LSKBitmap: ISKBitmap; LSKCanvas: ISKCanvas; LPaint: ISKPaint; begin Result := TBitmap.Create; try // 创建对应尺寸的SKBitmap,背景设为白色 LSKBitmap := TSKBitmap.Create(SkPaintBox1.Width, SkPaintBox1.Height, TSKColorType.RGBA8888); LSKBitmap.Erase(TSKColors.White); // 绘制签名路径 LSKCanvas := TSKCanvas.Create(LSKBitmap); LPaint := TSKPaint.Create; LPaint.Style := TSKPaintStyle.Stroke; LPaint.Color := TSKColors.Black; LPaint.StrokeWidth := 2; LSKCanvas.DrawPath(FSignaturePath, LPaint); // 转换为VCL TBitmap LSKBitmap.ToBitmap(Result); except Result.Free; raise; end; end;
调用示例:
var LBitmap: TBitmap; begin LBitmap := SignatureToBitmap; try // 使用LBitmap,比如赋值给Image控件 Image1.Picture.Assign(LBitmap); finally LBitmap.Free; end; end;
保存到文件
直接利用SKBitmap的EncodeToFile方法,将签名保存为PNG/JPG等格式:
procedure TForm1.SaveSignatureToFile(const AFileName: string); var LSKBitmap: ISKBitmap; LSKCanvas: ISKCanvas; LPaint: ISKPaint; begin LSKBitmap := TSKBitmap.Create(SkPaintBox1.Width, SkPaintBox1.Height, TSKColorType.RGBA8888); LSKBitmap.Erase(TSKColors.White); LSKCanvas := TSKCanvas.Create(LSKBitmap); LPaint := TSKPaint.Create; LPaint.Style := TSKPaintStyle.Stroke; LPaint.Color := TSKColors.Black; LPaint.StrokeWidth := 2; LSKCanvas.DrawPath(FSignaturePath, LPaint); // 保存为PNG,可替换为TSKEncodedImageFormat.Jpeg等格式 LSKBitmap.EncodeToFile(AFileName, TSKEncodedImageFormat.Png); end;
调用示例:
SaveSignatureToFile('C:\temp\signature.png');
内容的提问来源于stack exchange,提问作者Richard Shuck
相关产品推荐
相关产品推荐

