標籤:
Delphi的VCL類庫中,預設使用的是GDI繪圖介面,該介面封裝了Win32 GDI介面,能夠滿足基本的繪圖功能,但如果要實現更進階的繪圖功能,往往比較困難,GDI+是微軟在GDI之後的一個圖形介面,功能比GDI豐富很多,在VCL中使用GDI+,能夠實現很多進階繪圖功能。
目前有多種Delphi對GDI+的封裝實現,以下介紹最簡單的兩種:
1、使用Delphi內建的GDI+介面
首先,建立一個VCL Form應用,視窗檔案如下:
Pascal Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
object GDIPlusDemoForm1: TGDIPlusDemoForm1 Left = 0 Top = 0 Caption = ‘GDIPlusDemoForm1‘ ClientHeight = 247 ClientWidth = 524 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = ‘Tahoma‘ Font.Style = [] OldCreateOrder = False PixelsPerInch = 96 TextHeight = 13 object pb1: TPaintBox Left = 24 Top = 16 Width = 473 Height = 209 OnPaint = pb1Paint end end |
代碼如下:
Pascal Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
|
unit GDIPlusDemo1;
interface
uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Winapi.GDIPAPI, Winapi.GDIPOBJ, Winapi.GDIPUTIL;
type TGDIPlusDemoForm1 = class(TForm) pb1: TPaintBox; procedure pb1Paint(Sender: TObject); private { Private declarations } public { Public declarations } end;
var GDIPlusDemoForm1: TGDIPlusDemoForm1;
implementation
{$R *.dfm}
procedure TGDIPlusDemoForm1.pb1Paint(Sender: TObject); var g: TGPGraphics; p: TGPPen; b: TGPBrush; r: TGPRect; begin g := TGPGraphics.Create(pb1.Canvas.Handle); p := TGPPen.Create(aclRed, 2); b := TGPSolidBrush.Create(aclAliceBlue); try r := MakeRect(20, 20, 100, 60); g.FillRectangle(b, r); g.DrawRectangle(p, r); finally p.Free; b.Free; g.Free; end; end;
end. |
以下是運行結果:
其中Winapi.GDIPAPI, Winapi.GDIPOBJ, Winapi.GDIPUTIL三個單元是Delphi提供的對GDI+的封裝,可以看到使用GDI+是很方便的。
仔細看代碼可以發現,使用Delphi內建的GDI+支援,還是有些不足,關鍵的地方是所有的繪圖對象都是普通的對象,需要手工釋放,增加了很多不必要的代碼。
Delphi利用介面可以實現自動的垃圾收集,所以使用介面可以有效地簡化代碼。
http://blog.sina.com.cn/s/blog_591968570102vwsw.html
Delphi中使用GDI+進行繪圖(1)