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