Have an amazing solution built in RAD Studio? Let us know. Looking for discounts? Visit our Special Offers page!

Delphi 2010 DirectWrite “Hello World” Example

Author: Sinisa P29531

In my previous post I have translated Windows 7 SDK Direct2D “Advanced Geometries” example from C++ to Delphi 2010 code. That was a lot of fun, so I have decided to continue the adventure in the realm of Direct2D programming and this time converted one of the DirectWrite examples – DirectWrite sample “Hello World”.

Delphi 2010 Hello World DirectWrite sample app

Delphi 2010 Hello World DirectWrite sample app

In order to avoid writing over and over again the same Direct2D-specific code for creating TDirect2DCanvas instance and implementing “Resize” and “WMEraseBkgnd” methods, I have decided to refactor this common code into a reusable base class called “TFormD2D”.

Using this base Direct2D class is simple. If you want to “Direct2D-enable” a VCL form class, just add “D2DUtils” unit to your project, add “D2DUtils” to the “uses” clause in the interface section of your form’s unit, and change your form’s base class from “TForm” to “TForm2D”.
Now you only need to override “CreateD2DResources” and “PaintD2D” virtual methods and declare private members for different resources used for painting. In the first step you should create all Direct2D resources needed for painting like brushes, fonts, pens, geometries, and assign them to private variables in your form class. The second step is to implement “PaintD2D” that will include your painting code, most likely using “rt” convenience method that returns “D2DCanvas.RenderTarget” interface.

This is the actual code that paints “‘Hello World using DirectWrite in Delphi 2010”. Note that the form class derives from “TFormD2” and not “TForm”.

The “TForm38” class derives from “TFormD2” class. We need two Direct2D resources to render “Hello World”: a text format reference and a black brush. That’s why the first thing to do is to define two fields in our form class:

In the “D2DCreateResource” method both fields are initialized and they are used in “PaintD2D” for rendering text on the form. In order to simplify code that needs to be there for painting surrounding calls to “D2DCanvas.BeginDraw” and “D2DCanvas.EndDraw” have been moved to the ancestor class and very frequently used calls to “D2DCanvas.RenderTarget. …” have been replaced with “rt” function that returns the same thing, but with fewer lines of code.

The source code for this application can be downloaded from EDN CodeCentral.

Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.
Start Free Trial   Upgrade Today

   Free Delphi Community Edition   Free C++Builder Community Edition

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.