其他分享
首页 > 其他分享> > android-在图像上绘制文本

android-在图像上绘制文本

作者:互联网

我正在尝试使用以下代码在图像上绘制文本:

procedure TfMain.TextToImage(const AText: string; const AImage: TImage);
begin
  if NOT Assigned(AImage) then Exit;    
  AImage.Canvas.BeginScene;
  AImage.Canvas.Font.Size    := 18;
  AImage.Canvas.Font.Family  := 'Arial';
  AImage.Canvas.Fill.Color   := TAlphaColorRec.Dodgerblue;
  AImage.Canvas.Font.Style   := [TFontStyle.fsbold];
  AImage.Canvas.FillText( AImage.AbsoluteRect,
                          AText,
                          False,
                          1,
                          [TFillTextFlag.RightToLeft],
                          TTextAlign.taCenter,
                          TTextAlign.taCenter);
  AImage.Canvas.EndScene;
end;

问:为什么以上过程可在Windows上运行但不能在android上运行?

解决方法:

尝试直接在timage的TBitmap上绘制,而不是在TImage的Canvas上绘制.

在尝试访问图像之前,还需要创建图像的位图:

AImage.Bitmap := TBitmap.Create(Round(AImage.Width), Round(AImage.Height));

因此正确的代码将如下所示:

procedure TfMain.TextToImage(const AText: string; const AImage: TImage);
begin
  if NOT Assigned(AImage) then Exit;
  AImage.Bitmap := TBitmap.Create(Round(AImage.Width), Round(AImage.Height));
  AImage.Bitmap.Canvas.BeginScene;
  try
    //....
    // Use AImage.Bitmap.Canvas as needed
    AImage.Bitmap.Canvas.FillText( AImage.AbsoluteRect,
                            AText,
                            False,
                            1,
                            [],
                            TTextAlign.Center,
                            TTextAlign.Center);
  finally
    AImage.Bitmap.Canvas.EndScene;
  end;
end;

从TImage.Paint事件代码中,您将看到:

procedure TImage.Paint;
var
  R: TRectF;
begin
  if (csDesigning in ComponentState) and not Locked and not FInPaintTo then
  begin
    R := LocalRect;
    InflateRect(R, -0.5, -0.5);
    Canvas.DrawDashRect(R, 0, 0, AllCorners, AbsoluteOpacity, $A0909090);
  end;

  UpdateCurrentBitmap;
  if FCurrentBitmap <> nil then
    DrawBitmap(Canvas, LocalRect, FCurrentBitmap, AbsoluteOpacity);
end;

因此,无论您要在画布上绘画什么,在下一次重新绘画时,它将再次绘制完整的位图,从而擦除您已经完成的工作.

如果您不想触摸位图,则需要重写TImage的OnPaint事件并调用函数TextToImage(const AText:string; const AImage:TImage);

标签:delphi-10-seattle,firemonkey,android,delphi
来源: https://codeday.me/bug/20191026/1934948.html