Code behaves differently in Android and Windows

2019-04-15 17:09发布

问题:

I try to draw on a bitmap. This works fine in Windows but creates a segmentation fault in Android (anyhow, that's what Delphi says, I just see no reaction on Android). I have a mobile project, form containing only a TToolbar, TSpeedButton, two TLabels and a TImage. There's just one eventhandler for the TSpeedButton click.

When I comment out everything below the comment the code works fine in Android. When I try to follow with the debugger the code works fine to the end of the procedure. without seeing a drawing or a segmantation fault. When I let it run on the fault occurs.

What am I doing wrong?

procedure TForm2.Button_DrawClick (Sender: TObject);
var rct: TRectF;
    h, w: Int32;
begin
  h := Trunc (Image.Height);
  w := Trunc (Image.Width);
  Label_Height.Text := IntToStr (h);
  Label_Width .Text := IntToStr (w);
  rct := TRectF.Create(20, 20, w - 20, h - 20);
// can be commented out below //
  Image.Bitmap.Create (w, h);
  if Image.Bitmap.Canvas.BeginScene then
  try
    Image.Bitmap.Canvas.Stroke.Color := $FF0000FF;
    Image.Bitmap.Canvas.StrokeThickness := 3;
    Image.Bitmap.Canvas.DrawEllipse (rct, 20);
    Image.Bitmap.Canvas.Stroke.Color := $FF00FF00;
    Image.Bitmap.Canvas.DrawRect(rct, 0, 0, AllCorners, 40);
  finally
    Image.Bitmap.Canvas.EndScene;
  end; // try..finally
end; // Button_DrawClick //

回答1:

This code is wrong on all platforms.

Image.Bitmap.Create (w, h);

That runs the constructor on an already constructed instance. You don't want to do that. You might get away with it on some platforms but it's never right.

Set the bitmap dimensions like this:

Image.Bitmap.SetSize(w, h);    

You may want to call Clear on the bitmap too.