这个例子展示了如何使用TBitmap.Canvas属性。这个示例在图像上绘制了一个矩形。
要构建和测试这个例子,请创建一个多设备应用程序--Delphi,然后将下一个对象添加到表单中。
一个TImage来显示初始TBitmap.
一个TImage用于显示结果。
两个TLabel,每个TImage一个。
一个TButton,用于在初始图像上绘制。
一个TOpenDialog和一个TButton用于加载要定制的图像。
在加载按钮的OnClick事件处理程序中添加以下代码。
泰山老父完整Delphi 10.3.3 代码如下所示:
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Objects,FMX.DialogService;
type
TForm1 = class(TForm)
Image1: TImage;
Image2: TImage;
Label1: TLabel;
Label2: TLabel;
Button1: TButton;
OpenDialog1: TOpenDialog;
Button2: TButton;
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.Button1Click(Sender: TObject);
var
MyBitmap: TBitmap;
MyRect: TRectF;
begin
MyBitmap := TBitmap.Create(0, 0);
try
if Image1.Bitmap.IsEmpty then
// Display a message when there is no image loaded
TDialogService.MessageDialog(
'There is no image to customize:',
TMsgDlgType.mtWarning, mbYesNo, TMsgDlgBtn.mbYes,0,nil)
else
begin
// The rectangle to be drawn on the canvas
MyRect.Create(50, 30, 150, 200); // A record on the stack, does not Free
// A copy of the initial bitmap
MyBitmap.Assign(Image1.Bitmap);
// Draw a rectangle on the copy
with MyBitmap.Canvas do
begin
BeginScene;
Stroke.Kind := TBrushKind.Solid;
Stroke.Color := TAlphaColorRec.Lime;
Stroke.Thickness:=4;
DrawRect(MyRect, 20, 20, AllCorners, 1.0);
EndScene
end;
// Display the result
Image2.Bitmap := MyBitmap;
end;
finally
MyBitmap.Free;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
Image1.Bitmap.LoadFromFile(OpenDialog1.FileName);
end;
end;
end.