GDI+是微軟公司推出的新一代圖形設備接口,功能強大。不再像傳統的GDI那樣讓人的心志嚴重地受挫,GDI+具有很多新特性(如支持Alpha、漸 變色填充、反鋸齒等),並具有面向對象特性,這使得開發人員可以更方便、更形象地進行GDI+開發。有關GDI+更詳細的介紹大家可以查閱MSDN中的專 欄。
但目前在BCB環境中使用GDI+進行開發則還需要進行一定的設置和步驟才能成功編譯和鏈接。以下我就以BCB6為例進行簡單的說明:
1、建立編譯鏈接環境:
GDI+主要是通過gdiplus.dll進行調用,而BCB沒有直接提供與 gdiplus.dll對應的靜態鏈接庫,所以需要我們自己建立。如果在自己的計算機沒有找到文件gdiplus.dll,可以到微軟的官方網站進行下 載。然後復制一份到自己的工程目錄中,然後使用BCB提供的工具implib生成對應的靜態鏈接庫:
implib gdiplus.lib gdiplus.dll
完成後切記要把gdiplus.lib添加到工程中(使用BCB的"Project->Add to project..."命令)。
(注意:這兩個文章都需要保存在工程目錄中)
2、修改編譯選項:
打開BCB菜單"Project->Options",點擊"Directories/Conditionals"頁,在"Conditionals defines:"中添加「STRICT」編譯選項,如果有多項則需要用分號";"進行分隔。
3、在.cpp文件中的語句「#pragma hdrstop」後加入以下內容:
#include <algorithm>
using std::min;
using std::max;
4、在.cpp文件中的語句塊「#pragma package(smart_init)...」後加入以下內容:
using namespace Gdiplus;
(可以參閱後面的源碼例子)
5、最後注意要在.h文件中引入GDI+的頭文件:
#include <Gdiplus.h>
6、現在就可以進行基於GDI+的開發了,下面是我為大家編寫的一個產生旋轉的正方形的簡單動畫效果的例子:
(注意:需要添加一個Timer控件,並設置其Interval屬性為50)
Unit1.h:
//---------------------------------------------------------------------------
#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <Classes.hpp>
|
Unit1.cpp:
//---------------------------------------------------------------------------
#include <vcl.h>
#include <math.h>
#pragma hdrstop
#include <algorithm>
using std::min;
using std::max;
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
using namespace Gdiplus;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
DoubleBuffered = true;
// 初始化GDI+
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
}
//---------------------------------------------------------------------------
__fastcall TForm1::~TForm1()
{
// 閉關GDI+
GdiplusShutdown(gdiplusToken);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
const static int OX = 200, OY = 200;
const static REAL C = 140;
const static REAL PI = 3.14;
static REAL offset = 0;
POINT p[4];
REAL k[4];
// 生成正文形四角的新坐標值
for (int i=0; i < 4; i++)
{
k[i] = offset + (PI / 2) * i;
p[i].x = (int)OX + C * sin(k[i]);
p[i].y = (int)OY + C * cos(k[i]);
}
Gdiplus::Graphics g(Canvas->Handle);
g.SetSmoothingMode(SmoothingModeHighQuality); //高畫質、低速
// 重新填充背景
SolidBrush brush(Color::Color(0,0,0));
Pen pen(Color::Color(255, 255, 0), 3);
g.FillRectangle(&brush, 0, 0, ClientWidth, ClientHeight);
Gdiplus::Point point1(p[0].x, p[0].y);
Gdiplus::Point point2(p[1].x, p[1].y);
Gdiplus::Point point3(p[2].x, p[2].y);
Gdiplus::Point point4(p[3].x, p[3].y);
Gdiplus::Point point5(p[0].x, p[0].y);
// 在新坐標繪畫正方形
Gdiplus::Point points[] = {point1, point2, point3, point4, point5};
g.DrawLines(&pen, points, 5);
offset += 0.1;
}
//---------------------------------------------------------------------------
