【发布时间】:2021-09-01 10:22:30
【问题描述】:
我使用TSVGImageIcon 来读取 SVG 矢量图像,并且我创建了这个例程来将图像保存为特定大小的位图:
function SVG2Bitmap(Imatge: TBytes; x, y: integer): TBytes;
var SVG: TSVGIconImage;
Stream: TBytesStream;
Bitmap: TBitmap;
Resultat: TBytesStream;
Form: TForm;
begin
try
SVG := nil;
Form := nil;
Stream := nil;
Bitmap := nil;
Resultat := nil;
Stream := TBytesStream.Create(Imatge);
Stream.Position := 0;
Form := TForm.Create(nil); // The SVGIconImage raises an error if not inside a Form
SVG := TSVGIconImage.Create(Form);
SVG.Parent := Form;
SVG.Stretch := True;
SVG.Proportional := True;
SVG.LoadFromStream(Stream);
SVG.Width := x;
SVG.Height := y;
Bitmap := TBitmap.Create;
Bitmap.SetSize(x, y);
SVG.PaintTo(Bitmap.Canvas, 0, 0);
Resultat := TBytesStream.Create;
Bitmap.SaveToStream(Resultat);
Result := Resultat.Bytes;
finally
if Assigned(SVG) then try SVG.Free except end;
if Assigned(Form) then try Form.Free except end;
if Assigned(Bitmap) then try Bitmap.Free except end;
if Assigned(Stream) then try Stream.Free except end;
if Assigned(Resultat) then try Resultat.Free except end;
end;
end;
效果很好,但它会将透明区域填充为灰色,我希望它们为白色。你能推荐一种在设置透明度颜色的同时将 SVG 导出到位图的方法,还是我应该循环通过位图将灰色像素更改为白色?。
谢谢。
【问题讨论】:
-
由于
X.Free执行if Assigned(X) then X.Destroy,您的if Assigned(X) then X.Free执行if Assigned(X) then if Assigned(X) then X.Destroy。你看到冗余了吗? -
感谢@AndreasRejbrand,我不知道 x.Free 检查 X 是否已分配。我写了很多不必要的检查:-)。
-
我不确定,但我猜
SVG.PaintTo只会渲染 SVG 图像的不透明部分。如果是这样,那么在绘制 SVG 之前用所需的颜色填充位图将解决您的问题。 -
是
.SetFixedColor()吗? -
尝试更改位图的
Canvas.Brush.Color,如提到的here。