Delphi 5 Chapter 8
Delphi 5 Chapter 8
8
GDI and Fonts
IN THIS CHAPTER
• Delphi’s Representation of Pictures:
TImage 58
• Saving Images 60
• Summary 151
11.65227_Ch08CDx 11/30/99 11:22 AM Page 58
Advanced Techniques
58
PART II
In previous chapters, you worked with a property called Canvas. Canvas is appropriately
named because you can think of a window as an artist’s blank canvas on which various
Windows objects are painted. Each button, window, cursor, and so on is nothing more than a
collection of pixels in which the colors have been set to give it some useful appearance. In fact,
think of each individual window as a separate surface on which its separate components are
painted. To take this analogy a bit further, imagine that you’re an artist who requires various
tools to accomplish your task. You need a palette from which to choose different colors. You’ll
probably use different styles of brushes, drawing tools, and special artist’s techniques as well.
Win32 makes use of similar tools and techniques—in the programming sense—to paint the
various objects with which users interact. These tools are made available through the Graphics
Device Interface, otherwise known as the GDI.
Win32 uses the GDI to paint or draw the images you see on your computer screen. Before
Delphi, in traditional Windows programming, programmers worked directly with the GDI
functions and tools. Now, the TCanvas object encapsulates and simplifies the use of these func-
tions, tools, and techniques. This chapter teaches you how to use TCanvas to perform useful
graphics functions. You’ll also see how you can create advanced programming projects with
Delphi 5 and Win32 GDI. We illustrate this by creating a paint program and animation program.
In memory, both DDBs and DIBs are represented with the same structures, for the
most part. One key difference is that DDBs use the palette provided by the system,
whereas DIBs provide their own palette. To take this explanation further, DDBs are
simply native storage, handled by video driver routines and video hardware. DIBs are
standardized pixel formats, handled by GDI generic routines and stored in global
memory. Some video cards use DIB pixel formats as native storage, so you get
DDB=DIB. In general, DIB gives you more flexibility and simplicity, sometimes at a
slight performance cost. DDBs are always faster but not as convenient.
Metafiles
Unlike bitmaps, metafiles are vector-based graphical images. Metafiles are files in
which a series of GDI routines are stored, enabling you to save GDI function calls to
disk so that you can redisplay the image later. This also enables you to share your
drawing routines with other programs without having to call the specific GDI func-
tions in each program. Other advantages to metafiles are that they can be scaled to
arbitrary dimensions and still retain their smooth lines and arcs—bitmaps don’t do
this as well. In fact, this is one of the reasons the Win32 printing engine is built
around the enhanced metafile storage for print jobs.
There are two metafile formats: standard metafiles, typically stored in a file with a .wmf 8
extension, and enhanced metafiles, typically stored in a file with an .emf extension.
PROGRAMMING
Standard metafiles are a holdover from the Win16 system. Enhanced metafiles are
GRAPHICS
more robust and accurate. Use EMFs if you’re producing metafiles for your own appli-
cations. If you’re exporting your metafiles to older programs that might not be able
to use the enhanced format, use the 16-bit WMFs. Know, however, that by stepping
down to the 16-bit WMFs, you’ll also lose several GDI primitives that EMFs support
but WMFs do not. Delphi 5’s TMetafile class knows about both types of metafiles.
Icons
Icons are Win32 resources that usually are stored in an icon file with an .ico exten-
sion. They may also reside in a resource file (.res). There are two typical sizes of icons
in Windows: large icons that are 32×32 pixels, and small icons that are 16×16 pixels.
All Windows applications use both icon sizes. Small icons are displayed in the applica-
tion’s upper-left corner of the main window and also in the Windows List view con-
trol. Delphi’s encapsulation of this control is the TListView component. This control
appears on the Win32 page of the Component Palette.
Icons are made up of two bitmaps. One bitmap, referred to as the image, is the
actual icon image as it is displayed. The other bitmap, referred to as the mask, makes
it possible to achieve transparency when the icon is displayed. Icons are used for a
variety of purposes. For example, icons appear on an application’s taskbar and in mes-
sage boxes where the question mark, exclamation point, or stop sign icons are used
as attention grabbers.
11.65227_Ch08CDx 11/30/99 11:22 AM Page 60
Advanced Techniques
60
PART II
TPicture is a container class for the TGraphic abstract class. A container class means that
TPicture can hold a reference to and display a TBitmap, TMetafile, TIcon, or any other
TGraphic type, without really caring which is which. You use TImage.Picture’s properties and
methods to load image files into a TImage component. For example, use the following statement:
MyImage.Picture.LoadFromFile(‘FileName.bmp’);
Use a similar statement to load icon files or metafiles. For example, the following code loads a
Win32 metafile:
MyImage.Picture.LoadFromFile(‘FileName.emf’);
In Delphi 5, TPicture can now load JPEG images using the same technique for loading
bitmaps:
MyImage.Picture.LoadFromFile(‘FileName.jpeg’);
Saving Images
To save an image use the SaveToFile() method:
MyImage.Picture.SaveToFile(‘FileName.bmp’);
The TBitmap class encapsulates the Win32 bitmap and palette, and it provides the methods to
load, store, display, save, and copy the bitmapped images. TBitmap also manages palette real-
ization automatically. This means that the tedious task of managing bitmaps has been simpli-
fied substantially with Delphi 5’s TBitmap class, which enables you to focus on using the
bitmap and frees you from having to worry about all the underlying implementation details.
NOTE
TBitmap isn’t the only object that manages palette realization. Components such as
TImage, TMetafile, and every other TGraphic descendant also realize their bitmaps’
palettes on request. If you build components that contain a TBitmap object that
might have 256-color images, you’ll need to override your component’s GetPalette()
method to return the color palette of the bitmap.
To create an instance of a TBitmap class and load a bitmap file, for example, you use the fol-
lowing commands:
MyBitmap := TBitmap.Create;
MyBitmap.LoadFromFile(‘MyBMP.BMP’);
11.65227_Ch08CDx 11/30/99 11:22 AM Page 61
CAUTION
To copy one bitmap to another, you use the TBitmap.Assign() method, as in this example:
Bitmap1.Assign(Bitmap2);
You also can copy a portion of a bitmap from one TBitmap instance to another TBitmap
instance or even to the form’s canvas by using the CopyRect() method:
var
R1: TRect;
begin
with R1 do
begin
Top := 0;
Left := 0; 8
Right := BitMap2.Width div 2;
PROGRAMMING
Bottom := BitMap2.Height div 2;
GRAPHICS
end;
Bitmap1.Canvas.CopyRect(ClientRect, BitMap2.Canvas, R1);
end;
In the preceding code, you first calculate the appropriate values in a TRect record and then use
the TCanvas.CopyRect() method to copy a portion of the bitmap. A TRect is defined as fol-
lows:
TRect = record
case Integer of
0: (Left, Top, Right, Bottom: Integer);
1: (TopLeft, BottomRight: TPoint);
end;
This technique will be used in the paint program later in the chapter. CopyRect() automatically
stretches the copied portion of the source canvas to fill the destination rectangle.
CAUTION
continues
11.65227_Ch08CDx 11/30/99 11:22 AM Page 62
Advanced Techniques
62
PART II
use in that two separate copies of the image exist in memory. The Assign() technique
costs nothing because the two bitmap objects will share a reference to the same image
in memory. If you happen to modify one of the bitmap objects, VCL will clone the
image using a copy-on-write scheme.
Another method you can use to copy the entire bitmap to the form’s canvas so that it shrinks or
expands to fit inside the canvas’s boundaries is the StretchDraw() method. Here’s an example:
Canvas.StretchDraw(R1, MyBitmap);
Using Pens
In this section, we first explain how to use the TPen properties and then show you some code in
a sample project that uses these properties.
Pens enable you to draw lines on the canvas and are accessed from the Canvas.Pen property.
You can change how lines are drawn by modifying the pen’s properties: Color, Width, Style,
and Mode.
The Color property specifies a pen’s color. Delphi 5 provides predefined color constants that
match many common colors. For example, the constants clRed and clYellow correspond to
the colors red and yellow. Delphi 5 also defines constants to represent the Win32 system screen
element colors such as clActiveCaption and clHighlightText, which correspond to the
Win32 active captions and highlighted text. The following line assigns the color blue to the
canvas’s pen:
Canvas.Pen.color := clblue;
This line shows you how to assign a random color to Canvas’s Pen property:
Pen.Color := TColor(RGB(Random(255),Random(255), Random(255)));
green, and blue intensity levels. It returns a Win32 color as a long integer value. This
is represented as a TColor Delphi type. There are 255 possible values for each inten-
sity level and approximately 16 million colors that can be returned from the RGB()
function. RGB(0, 0, 0), for example, returns the color value for black, whereas
RGB(255, 255, 255) returns the color value for white. RGB(255, 0 ,0), RGB(0, 255,
0), and RGB(0, 0, 255) return the color values for red, green, and blue, respectively.
By varying the values passed to RGB(), you can obtain a color anywhere within the
color spectrum.
TColor is specific to VCL and refers to constants defined in the Graphics.pas unit.
These constants map to either the closest matching color in the system palette or to a
defined color in the Windows Control Panel. For example, clBlue maps to the color
blue whereas the clBtnFace maps to the color specified for button faces. In addition
to the three bytes to represent the color, TColor’s highest order byte specifies how a
color is matched. Therefore, if the highest order byte is $00, the represented color is
the closest matching color in the system palette. A value of $01 represents the closest
matching color in the currently realized palette. Finally, a color of $02 matches with
the nearest color in the logical palette of the current device context. You will find
additional information in the Delphi help file under “TColor type.”
8
PROGRAMMING
GRAPHICS
TIP
Use the ColorToRGB() function to convert Win32 system colors, such as clWindow, to
a valid RGB color. The function is described in Delphi 5’s online help.
The pen can also draw lines with different drawing styles, as specified by its Style property.
Table 8.1 shows the different styles you can set for Pen.Style.
Advanced Techniques
64
PART II
The following line shows how you would change the pen’s drawing style:
Canvas.Pen.Style := psDashDot;
Figure 8.1 shows how the different pen styles appear when drawn on the form’s canvas. One
thing to note: The “in between” colors in the stippled lines come from the brush color. If you
want to make a black dashed line run across a red square, you would need to set the
Canvas.Brush.Color to clRed or set the Canvas.Brush.Style to bsClear. Setting both the
pen and brush color is how you would draw, for example, a red and blue dashed line across a
white square.
FIGURE 8.1
Different pen styles.
The Pen.Width property enables you to specify the width, in pixels, that the pen uses for draw-
ing. When this property is set to a larger width, the pen draws with thicker lines.
NOTE
The stipple line style applies only to pens with a width of 1. Setting the pen width to
2 will draw a solid line. This is a holdover from the 16-bit GDI that Win32 emulates
for compatibility. Windows 95/98 does not do fat stippled lines, but Windows
NT/2000 can if you use only the extended GDI feature set.
Three factors determine how Win32 draws pixels or lines to a canvas surface: the pen’s color,
the surface or destination color, and the bitwise operation that Win32 performs on the two-
color values. This operation is known as a raster operation (ROP). The Pen.Mode property
specifies the ROP to be used for a given canvas. Sixteen modes are predefined in Win32, as
shown in Table 8.2.
11.65227_Ch08CDx 11/30/99 11:22 AM Page 65
TABLE 8.2 Win32 Pen Modes on Source Pen.Color (S) and Destination (D) Color
Mode Result Pixel Color Boolean Operation
pmBlack Always black 0
pmWhite Always white 1
pmNOP Unchanged D
pmNOT Inverse of D color not D
pmCopy Color specified by S S
pmNotCopy Inverse of S not S
pmMergePenNot Combination S and inverse of D S or not D
pmMaskPenNot Combination of colors common S and not D
to S and inverse of D
pmMergeNotPen Combination of D and inverse not S or D
of S
pmMaskNotPen Combination of colors common not S and D
to D and inverse of S
pmMerge Combination of S and D S or D 8
pmNotMerge Inverse of pmMerge operation not (S or D)
PROGRAMMING
on S and D
GRAPHICS
pmMask Combination of colors common S and D
to S and D
pmNotMask Inverse of pmMask operation not (S and D)
on S and D
pmXor Combination of colors in S XOR D
either S or D but not both
pmNotXor Inverse of pmXOR operation not (S XOR D)
on S and D
Pen.mode is pmCopy by default. This means that the pen draws with the color specified by its
Color property. Suppose that you want to draw black lines on a white background. If a line
crosses over a previously drawn line, it should draw white rather than black.
One way to do this would be to check the color of the area you’re going to draw to—if it’s
white, set pen.Color to black; if it is black, set pen.Color to white. Although this approach
works, it would be cumbersome and slow. A better approach would be to set Pen.Color to
clBlack and Pen.Mode to pmNot. This would result in the pen drawing the inverse of the merg-
ing operation with the pen and surface color. Figure 8.2 shows you the result of this operation
when drawing with a black pen in a crisscross fashion.
11.65227_Ch08CDx 11/30/99 11:22 AM Page 66
Advanced Techniques
66
PART II
FIGURE 8.2
The output of a pmNotMerge operation.
Listing 8.1 is an example of the project on the CD that illustrates the code that resulted in
Figures 8.1 and 8.2. You’ll find this demo on the CD.
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms,
Dialogs, Menus, StdCtrls, Buttons, ExtCtrls;
type
TMainForm = class(TForm)
mmMain: TMainMenu;
mmiPens: TMenuItem;
mmiStyles: TMenuItem;
mmiPenColors: TMenuItem;
mmiPenMode: TMenuItem;
procedure mmiStylesClick(Sender: TObject);
procedure mmiPenColorsClick(Sender: TObject);
procedure mmiPenModeClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure ClearCanvas;
procedure SetPenDefaults;
end;
var
11.65227_Ch08CDx 11/30/99 11:22 AM Page 67
MainForm: TMainForm;
implementation
{$R *.DFM}
procedure TMainForm.ClearCanvas;
var
R: TRect;
begin
// Clear the contents of the canvas
with Canvas do
begin
Brush.Style := bsSolid;
Brush.Color := clWhite;
Canvas.FillRect(ClientRect);
end;
end;
procedure TMainForm.SetPenDefaults;
begin
with Canvas.Pen do
8
begin
PROGRAMMING
Width := 1;
GRAPHICS
Mode := pmCopy;
Style := psSolid;
Color := clBlack;
end;
end;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 68
Advanced Techniques
68
PART II
canvas.pen.Mode := pmNot;
while x < ClientWidth do
begin
Canvas.MoveTo(x, 0);
canvas.LineTo(x, ClientHeight);
inc(x, 30);
end;
end;
end.
Listing 8.1 shows three examples of dealing with the canvas’s pen. The two helper functions, 8
ClearCanvas() and SetPenDefaults(), are used to clear the contents of the main form’s can-
PROGRAMMING
vas and to reset the Canvas.Pen properties to their default values as these properties are modi-
GRAPHICS
fied by each of the three event handlers.
ClearCanvas() is a useful technique for erasing the contents of any component containing a
Canvas property. ClearCanvas() uses a solid white brush to erase whatever was previously
painted on the Canvas. FillRect() is responsible for painting a rectangular area as specified
by a TRect structure, ClientRect, which is passed to it.
The mmiStylesClick() method shows how to display the various TPen styles as shown in
Figure 8.1 by drawing horizontal lines across the form’s Canvas using a different TPen style.
Both TCanvas.MoveTo() and TCanvas.LineTo() enable you to draw lines on the canvas.
The mmiPenColorsClick() method illustrates drawing lines using a different TPen color. Here
you use the RGB() function to retrieve a color to assign to TPen.Color. The three values you
pass to RGB() are each random values within range of 0 to 255. The output of this method is
shown in Figure 8.3.
Finally, the mmiPenModeClick() method illustrates how to draw lines using a different pen
mode. Here you use the pmNot mode to perform the actions previously discussed, resulting in
the output shown in Figure 8.2.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 70
Advanced Techniques
70
PART II
FIGURE 8.3
Output from the mmiPenColorsClick() method.
It’s rare that you’ll ever have to access individual pixels on your form. In general, you do not
want to use the Pixels property because it’s slow. Accessing this property uses the
GetPixel()/SetPixel() GDI functions, which Microsoft has acknowledged are flawed and
will never be efficient. This is because both functions rely on 24-bit RGB values. When not
working with 24-bit RGB device contexts, these functions must perform serious color-matching
gymnastics to convert the RGB into a device pixel format. For quick pixel manipulation, use
the TBitmap.ScanLine array property instead. To fetch or set one or two pixels at a time, using
Pixels is okay.
Using Brushes
This section discusses the TBrush properties and shows you some code in a sample project that
uses these properties.
the pattern of the brush background, and Bitmap specifies a bitmap you can use to create cus-
tom patterns for the brush’s background.
Eight brush options are specified by the Style property: bsSolid, bsClear, bsHorizontal,
bsVertical, bsFDiagonal, bsBDiagonal, bsCross, and bsDiagCross. By default, the brush
color is clWhite with a bsSolid style and no bitmap. You can change the color and style to fill
an area with different patterns. The example in the following section illustrates using each of
the TBrush properties.
unit MainFrm;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, 8
Dialogs, Menus, ExtCtrls;
PROGRAMMING
GRAPHICS
type
TMainForm = class(TForm)
mmMain: TMainMenu;
mmiBrushes: TMenuItem;
mmiPatterns: TMenuItem;
mmiBitmapPattern1: TMenuItem;
mmiBitmapPattern2: TMenuItem;
procedure mmiPatternsClick(Sender: TObject);
procedure mmiBitmapPattern1Click(Sender: TObject);
procedure mmiBitmapPattern2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FBitmap: TBitmap;
public
procedure ClearCanvas;
end;
var
MainForm: TMainForm;
implementation
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 72
Advanced Techniques
72
PART II
procedure TMainForm.ClearCanvas;
var
R: TRect;
begin
// Clear the contents of the canvas
with Canvas do
begin
Brush.Style := bsSolid;
Brush.Color := clWhite;
GetWindowRect(Handle, R);
R.TopLeft := ScreenToClient(R.TopLeft);
R.BottomRight := ScreenToClient(R.BottomRight);
FillRect(R);
end;
end;
Brush.Style := bsClear;
Rectangle(10, 10, 100, 100);
Brush.Color := clBlack;
Brush.Style := bsSolid;
Rectangle(120, 10, 220, 100);
Brush.Style := bsSolid;
Brush.Color := clRed;
Rectangle(230, 0, 330, 90);
Brush.Style := bsCross;
Brush.Color := clBlack;
Rectangle(240, 10, 340, 100);
Brush.Style := bsBDiagonal;
Rectangle(10, 120, 100, 220);
Brush.Style := bsFDiagonal;
Rectangle(120, 120, 220, 220);
Brush.Style := bsDiagCross;
Rectangle(240, 120, 340, 220);
Brush.Style := bsHorizontal;
Rectangle(10, 240, 100, 340);
Brush.Style := bsVertical;
Rectangle(120, 240, 220, 340);
8
PROGRAMMING
end;
GRAPHICS
end;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 74
Advanced Techniques
74
PART II
end.
TIP
The ClearCanvas() method that you use here is a handy routine for a utility unit.
You can define ClearCanvas() to take TCanvas and TRect parameters to which the
erase code will be applied:
procedure ClearCanvas(ACanvas: TCanvas; ARect: TRect);
begin
// Clear the contents of the canvas
with ACanvas do
begin
Brush.Style := bsSolid;
Brush.Color := clWhite;
FillRect(ARect);
end;
end;
11.65227_Ch08CDx 11/30/99 11:23 AM Page 75
The mmiPatternsClick() method illustrates drawing with various TBrush patterns. First, you
draw out the titles and then, using each of the available brush patterns, draw rectangles on the
form’s canvas. Figure 8.4 shows the output of this method.
FIGURE 8.4
8
Brush patterns.
PROGRAMMING
The mmiBitmapPattern1Click() and mmiBitmapPattern2Click() methods illustrate how to
GRAPHICS
use a bitmap pattern as a brush. The TCanvas.Brush property contains a TBitmap property to
which you can assign a bitmap pattern. This pattern will be used to fill the area painted by the
brush instead of the pattern specified by the TBrush.Style property. There are a few rules for
using this technique, however. First, you must assign a valid bitmap object to the property.
Second, you must assign nil to the Brush.Bitmap property when you’re finished with it
because the brush does not take ownership of the bitmap object when you assign a bitmap to it.
Figures 8.5 and 8.6 show the output of mmiBitmapPattern1Click() and
mmiBitmapPattern2Click(), respectively.
NOTE
Windows limits the size of pattern brush bitmaps to 8×8 pixels, and they must be
device-dependent bitmaps, not device-independent bitmaps. Windows will reject
brush pattern bitmaps larger than 8×8; NT will accept larger but will only use the
top-left 8×8 portion.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 76
Advanced Techniques
76
PART II
FIGURE 8.5
Output from mmiBitmapPattern1Click().
FIGURE 8.6
Output from mmiBitmapPattern2Click().
TIP
Using a bitmap pattern to fill an area on the canvas doesn’t only apply to the form’s
canvas but also to any component that contains a Canvas property. Just access the
methods and/or properties of the Canvas property of the component rather than the
form. For example, here’s how to perform pattern drawing on a TImage component:
Image1.Canvas.Brush.Bitmap := SomeBitmap;
try
11.65227_Ch08CDx 11/30/99 11:23 AM Page 77
Using Fonts
The Canvas.Font property enables you to draw text using any of the available Win32 fonts.
You can change the appearance of text written to the canvas by modifying the font’s Color,
Name, Size, Height, or Style property.
You can assign any of Delphi 5’s predefined colors to Font.Color. The following code, for
example, assigns the color red to the canvas’s font:
Canvas.Font.Color := clRed;
The Name property specifies the Window’s font name. For example, the following two lines of
code assign different typefaces to Canvas’s font:
Canvas.Font.Name := ‘New Times Roman’;
8
Canvas.Font.Size specifies the font’s size in points.
PROGRAMMING
is a set composed of one style or a combination of the styles shown in
GRAPHICS
Canvas.Font.Style
Table 8.3.
To combine two styles, use the syntax for combining multiple set values:
Canvas.Font.Style := [fsBold, fsItalic];
You can use TFontDialog to obtain a Win32 font and assign that font to the TMemo.Font property:
if FontDialog1.Execute then
Memo1.Font.Assign(FontDialog1.Font);
The same can be done to assign the font selected in TFontDialog to the Canvas’s font:
Canvas.Font.Assign(FontDialog1.Font);
11.65227_Ch08CDx 11/30/99 11:23 AM Page 78
Advanced Techniques
78
PART II
CAUTION
Make sure to use the Assign() method when copying TBitMap, TBrush, TIcon,
TMetaFile, TPen, and TPicture instance variables. A statement such as
MyBrush1 := MyBrush2
might seem valid, but it performs a direct pointer copy so that both instances point
to the same brush object, which can result in a heap leak. By using Assign(), you
ensure that previous resources are freed.
This is not so when assigning between two TFont properties. Therefore, a statement
such as
Form1.Font := Form2.Font
is a valid statement because the TForm.Font is a property whose write method inter-
nally calls Assign() to copy the data from the given font object. Be careful, how-
ever; this is only valid with when assigning TFont properties, not TFont variables. As
a general rule, always use Assign().
Additionally, you can assign individual attributes from the selected font in TFontDialog to the
Canvas’s font:
Canvas.Font.Name := Font.Dialog1.Font.Name;
Canvas.Font.Size := Font.Dialog1.Font.Size;
We’ve quickly brushed over fonts here. A more thorough discussion on fonts appears at the end
of this chapter.
FIGURE 8.7
A form that contains two images to illustrate CopyMode.
PROGRAMMING
GRAPHICS
FIGURE 8.8
A copy operation using the cmSrcAnd copy mode setting.
FIGURE 8.9
A copy operation using the cmSrcInvert copy mode setting.
Listing 8.3 shows the source code for the project, illustrating the various copy modes. You’ll
find this code on the CD.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 80
Advanced Techniques
80
PART II
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TMainForm = class(TForm)
imgCopyTo: TImage;
imgCopyFrom: TImage;
cbCopyMode: TComboBox;
btnDrawImages: TButton;
btnCopy: TButton;
procedure FormShow(Sender: TObject);
procedure btnCopyClick(Sender: TObject);
procedure btnDrawImagesClick(Sender: TObject);
private
procedure DrawImages;
procedure GetCanvasRect(AImage: TImage; var ARect: TRect);
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
procedure TMainForm.DrawImages;
var
R: TRect;
begin
// Draw an ellipse in img1
with imgCopyTo.Canvas do
begin
Brush.Style := bsSolid;
Brush.Color := clWhite;
GetCanvasRect(imgCopyTo, R);
FillRect(R);
Brush.Color := clRed;
Ellipse(10, 10, 100, 100);
end;
PROGRAMMING
Ellipse(30, 30, 120, 120);
GRAPHICS
end;
end;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 82
Advanced Techniques
82
PART II
GetCanvasRect(imgCopyTo, CopyToRect);
GetCanvasRect(imgCopyFrom, CopyFromRect);
end.
This project initially paints an ellipse on the two TImage components: imgFromImage and
imgToImage. When the Copy button is clicked, imgFromImage is copied onto imgToImage1
using the CopyMode setting specified from cbCopyMode.
Other Properties
TCanvas has other properties that we’ll discuss more as we illustrate how to use them in coding
techniques. This section briefly discusses these properties.
TCanvas.ClipRect represents a drawing region of the canvas to which drawing can be per-
formed. You can use ClipRect to limit the area that can be drawn for a given canvas.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 83
CAUTION
Initially, ClipRect represents the entire Canvas drawing area. You might be tempted
to use the ClipRect property to obtain the bounds of a canvas. However, this could
get you into trouble. ClipRect will not always represent the total size of its compo-
nent. It can be less than the Canvas’s display area.
TCanvas.Handle gives you access to the actual device context that the TCanvas instance encap-
sulates. Device contexts are discussed later in this chapter.
TCanvas.PenPos is simply an X,Y coordinate location of the canvas’s pen. You can change the
pen’s position by using the TCanvas methods—MoveTo(), LineTo(), PolyLine(), TextOut(),
and so on.
PROGRAMMING
GRAPHICS
Drawing Lines with TCanvas
TCanvas.MoveTo() changes Canvas.Pen’s drawing position on the Canvas’s surface. The fol-
lowing code, for example, moves the drawing position to the upper-left corner of the canvas:
Canvas.MoveTo(0, 0);
TCanvas.LineTo() draws a line on the canvas from its current position to the position specified
by the parameters passed to LineTo(). Use MoveTo() with LineTo() to draw lines anywhere
on the canvas. The following code draws a line from the upper-left position of the form’s client
area to the form’s lower-right corner:
Canvas.MoveTo(0, 0);
Canvas.LineTo(ClientWidth, ClientHeight);
You already saw how to use the MoveTo() and LineTo() methods in the section covering the
TCanvas.Pen property.
NOTE
Delphi now supports right-to-left-oriented text and control layouts; some controls
(such as the grid) change the canvas coordinate system to flip the X axis. Therefore, if
you’re running Delphi on a Middle East version of Windows, MoveTo(0,0) may go to
the top-right corner of the window.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 84
Advanced Techniques
84
PART II
You also can fill an area on the canvas with a brush pattern specified in the
Canvas.Brush.Style property. The following code draws an ellipse and fills the ellipse inte-
rior with the brush pattern specified by Canvas.Brush.Style:
Canvas.Brush.Style := bsCross;
Canvas.Ellipse(0, 0, ClientWidth, ClientHeight);
Additionally, you saw how to add a bitmap pattern to the TCanvas.Brush.Bitmap property,
which it uses to fill an area on the canvas. You can also use a bitmap pattern for filling in
shapes. We’ll demonstrate this later.
Some of Canvas’s other shape-drawing methods take additional or different parameters to
describe the shape being drawn. The PolyLine() method, for example, takes an array of
TPoint records that specify positions, or pixel coordinates, on the canvas to be connected by a
line—sort of like connect the dots. A TPoint is a record in Delphi 5 that signifies an X,Y coor-
dinate. A TPoint is defined as
TPoint = record
X: Integer;
Y: Integer;
end;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics,
Controls, Forms, Dialogs, Menus;
type
TMainForm = class(TForm)
11.65227_Ch08CDx 11/30/99 11:23 AM Page 85
mmMain: TMainMenu;
mmiShapes: TMenuItem;
mmiArc: TMenuItem;
mmiChord: TMenuItem;
mmiEllipse: TMenuItem;
mmiPie: TMenuItem;
mmiPolygon: TMenuItem;
mmiPolyline: TMenuItem;
mmiRectangle: TMenuItem;
mmiRoundRect: TMenuItem;
N1: TMenuItem;
mmiFill: TMenuItem;
mmiUseBitmapPattern: TMenuItem;
mmiPolyBezier: TMenuItem;
procedure mmiFillClick(Sender: TObject);
procedure mmiArcClick(Sender: TObject);
procedure mmiChordClick(Sender: TObject);
procedure mmiEllipseClick(Sender: TObject);
procedure mmiUseBitmapPatternClick(Sender: TObject);
procedure mmiPieClick(Sender: TObject);
procedure mmiPolygonClick(Sender: TObject);
procedure mmiPolylineClick(Sender: TObject);
8
procedure mmiRectangleClick(Sender: TObject);
PROGRAMMING
procedure mmiRoundRectClick(Sender: TObject);
GRAPHICS
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure mmiPolyBezierClick(Sender: TObject);
private
FBitmap: TBitmap;
public
procedure ClearCanvas;
procedure SetFillPattern;
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
procedure TMainForm.ClearCanvas;
begin
// Clear the contents of the canvas
with Canvas do
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 86
Advanced Techniques
86
PART II
procedure TMainForm.SetFillPattern;
begin
{ Determine if shape is to be draw with a bitmap pattern in which
case load a bitmap. Otherwise, use the brush pattern. }
if mmiUseBitmapPattern.Checked then
Canvas.Brush.Bitmap := FBitmap
else
with Canvas.Brush do
begin
Bitmap := nil;
Color := clBlue;
Style := bsCross;
end;
end;
PROGRAMMING
Canvas.Ellipse(0, 0, ClientWidth, ClientHeight);
GRAPHICS
end;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 88
Advanced Techniques
88
PART II
end.
The main menu event handlers perform the shape-drawing functions. Two public methods,
ClearCanvas() and SetFillPattern(), serve as helper functions for the event handlers. The
11.65227_Ch08CDx 11/30/99 11:23 AM Page 89
first eight menu items result in a shape-drawing function being drawn on the form’s canvas.
The last two items, “Fill” and “Use Bitmap Pattern,” specify whether the shape is to be filled
with a brush pattern or a bitmap pattern, respectively.
You should already be familiar with the ClearCanvas() functionality. The SetFillPattern()
method determines whether to use a brush pattern or a bitmap pattern to fill the shapes drawn by
the other methods. If a bitmap is selected, it’s assigned to the Canvas.Brush.Bitmap property.
All the shape-drawing event handlers call ClearCanvas() to erase what was previously drawn
on the canvas. They then call SetFillPattern() if the mmiFill.Checked property is set to
True. Finally, the appropriate TCanvas drawing routine is called. The comments in the source
discuss the purpose of each function. One method worth mentioning here is
mmiPolylineClick().
When you’re drawing shapes, an enclosed boundary is necessary for filling an area with a
brush or bitmap pattern. Although it’s possible to use PolyLine() and FloodFill() to create
an enclosed boundary filled with a pattern, this method is highly discouraged. PolyLine() is
used specifically for drawing lines. If you want to draw filled polygons, call the
TCanvas.Polygon() method. A one-pixel imperfection in where the Polyline() lines are
drawn will allow the call to FloodFill() to leak out and fill the entire canvas. Drawing filled
shapes with Polygon() uses math techniques that are immune to variations in pixel placement. 8
PROGRAMMING
Painting Text with TCanvas
GRAPHICS
TCanvas encapsulates Win32 GDI routines for drawing text to a drawing surface. The follow-
ing sections illustrate how to use these routines as well as how to use Win32 GDI functions
that are not encapsulated by the TCanvas class.
var
S: String;
w, h: Integer;
begin
S := ‘Delphi 5 -- Yes!’;
w := Canvas.TextWidth(S);
h := Canvas.TextHeight(S);
end.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 90
Advanced Techniques
90
PART II
The TextRect() method also writes text to the form but only within a rectangle specified by a
TRect structure. The text not contained within the TRect boundaries is clipped. In the line
the string “Delphi 5 Yes!” is written to the canvas at location 0,0. However, the portion of
the string that falls outside the coordinates specified by R, a TRect structure, gets clipped.
Listing 8.5 illustrates using some of the text-drawing routines.
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Menus;
const
DString = ‘Delphi 5 YES!’;
DString2 = ‘Delphi 5 Rocks!’;
type
TMainForm = class(TForm)
mmMain: TMainMenu;
mmiText: TMenuItem;
mmiTextRect: TMenuItem;
mmiTextSize: TMenuItem;
mmiDrawTextCenter: TMenuItem;
mmiDrawTextRight: TMenuItem;
mmiDrawTextLeft: TMenuItem;
procedure mmiTextRectClick(Sender: TObject);
procedure mmiTextSizeClick(Sender: TObject);
procedure mmiDrawTextCenterClick(Sender: TObject);
procedure mmiDrawTextRightClick(Sender: TObject);
procedure mmiDrawTextLeftClick(Sender: TObject);
public
procedure ClearCanvas;
end;
var
MainForm: TMainForm;
implementation
11.65227_Ch08CDx 11/30/99 11:23 AM Page 91
{$R *.DFM}
procedure TMainForm.ClearCanvas;
begin
with Canvas do
begin
Brush.Style := bsSolid;
Brush.Color := clWhite;
FillRect(ClipRect);
end;
end;
PROGRAMMING
{ Initialize a TRect structure. The height of this rectangle will
GRAPHICS
be 1/2 the height of the text string height. This is to
illustrate clipping the text by the rectangle drawn }
R := Rect(1, THeight div 2, TWidth + 1, THeight+(THeight div 2));
// Draw a rectangle based on the text sizes
Canvas.Rectangle(R.Left-1, R.Top-1, R.Right+1, R.Bottom+1);
// Draw the Text within the rectangle
Canvas.TextRect(R,0,0,DString);
end;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 92
Advanced Techniques
92
PART II
end.
Like the other projects, this project contains the ClearCanvas() method to erase the contents
of the form’s canvas.
The various methods of the main form are event handlers to the form’s main menu.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 93
FIGURE 8.10
The output of mmiTextRectClick().
mmiTextSizeClick() shows how to determine the size of a text string using the
TCanvas.TextWidth() and TCanvas.TextHeight() methods. Its output is shown in Figure 8.11. 8
PROGRAMMING
GRAPHICS
FIGURE 8.11
The output of mmiTextSizeClick().
Advanced Techniques
94
PART II
If you look at the various GDI functions such as BitBlt() and DrawText(), you’ll find that
one of the required parameters is a DC, or device context. The device context is accessible
through the canvas’s Handle property. TCanvas.Handle is the DC for that canvas.
Device Contexts
Device contexts (DCs) are handles provided by Win32 to identify a Win32 application’s
connection to an output device such as a monitor, printer, or plotter through a device
driver. In traditional Windows programming, you’re responsible for requesting a DC
whenever you need to paint to a window’s surface; then, when done, you have to
return the DC back to Windows. Delphi 5 simplifies the management of DCs by
encapsulating DC management in the TCanvas class. In fact, TCanvas even caches your
DC, saving it for later so that requests to Win32 occur less often—thus, speeding up
your program’s overall execution.
To see how to use TCanvas with a Win32 GDI function, you used the GDI routine DrawText() to
output text with advanced formatting capabilities. DrawText takes the following five parameters:
Parameter Description
DC Device context of the drawing surface.
Str Pointer to a buffer containing the text to be drawn. This must be a
null-terminated string if the Count parameter is -1.
Count Number of bytes in Str. If this value is -1, Str is a pointer to a
null-terminated string.
Rect Pointer to a TRect structure containing the coordinates of the
rectangle in which the text is formatted.
Format A bit field that contains flags specifying the various formatting
options for Str.
In the example, you initialize a TRect structure using the Rect() function. You’ll use the struc-
ture to draw a rectangle around the text drawn with the DrawText() function. Each of the three
methods passes a different set of formatting flags to the DrawText() function. The
dt_WordBreak and dt_Center formatting flags are passed to the DrawText() function to center
the text in the rectangle specified by the TRect variable R. dt_WordBreak, OR’ed with
dt_Right, is used to right-justify the text in the rectangle. Likewise, dt_WordBreak, OR’ed with
dt_Left, left-justifies the text. The dt_WordBreak specifier word-wraps the text within the
width given by the rectangle parameter and modifies the rectangle height to bind the text after
being word-wrapped.
The output of mmiDrawTextCenterClick() is shown in Figure 8.12.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 95
FIGURE 8.12
The output of mmiDrawTextCenterClick().
TCanvas also has the methods Draw(), Copy(), CopyRect(), and StretchDraw(), which enable
you to draw, copy, expand, and shrink an image or a portion of an image to another canvas.
You’ll use CopyRect() when we show you how to create a paint program later in this chapter.
Also, Chapter 16, “MDI Applications,” shows you how to use the StretchDraw() method to
stretch a bitmap image onto the client area of a form.
8
Coordinate Systems and Mapping Modes
PROGRAMMING
GRAPHICS
Most GDI drawing routines require a set of coordinates that specify the location where draw-
ing is to occur. These coordinates are based on a unit of measurement, such as the pixel.
Additionally, GDI routines assume an orientation for the vertical and horizontal axis—that is,
how increasing or decreasing the values of the X,Y coordinates moves the position at which
drawing occurs. Win32 relies on two factors to perform drawing routines. These are the Win32
coordinates system and the mapping mode of the area that’s being drawn to.
Win32 coordinates systems are, generally, no different from any other coordinates system. You
define a coordinate for an X,Y axis, and Win32 plots that location to a point on your drawing
surface based on a given orientation. Win32 uses three coordinates systems to plot areas on
drawing surfaces called the device, logical, and world coordinates. Windows 95 doesn’t sup-
port world transformations (bitmap rotation, shearing, twisting, and so on). We’ll cover the first
two modes in this chapter.
Device Coordinates
Device coordinates, as the name implies, refer to the device on which Win32 is running. Its
measurements are in pixels, and the orientation is such that the horizontal and vertical axes
increase from left to right and top to bottom. For example, if you’re running Windows on a
640×480 pixel display, the coordinates at the top-left corner on your device are (0,0), whereas
the bottom-right coordinates are (639,479).
11.65227_Ch08CDx 11/30/99 11:23 AM Page 96
Advanced Techniques
96
PART II
Logical Coordinates
Logical coordinates refer to the coordinates system used by any area in Win32 that has a
device context or DC such as a screen, a form, or a form’s client area. The difference between
device and logical coordinates is explained in a moment. The screen, form window, and form
client-area coordinates are explained first.
Screen Coordinates
Screen coordinates refer to the display device; therefore, it follows that coordinates are based
on pixel measurements. On a 640×480 display, Screen.Width and Screen.Height are also 640
and 480 pixels, respectively. To obtain a device context for the screen, use the Win32 API func-
tion GetDC(). You must match any function that retrieves a device context with a call to
ReleaseDC(). The following code illustrates this:
var
ScreenDC: HDC;
begin
Screen DC := GetDC(0);
try
{ Do whatever you need to do with ScreenDC }
finally
ReleaseDC(0, ScreenDC);
end;
end;
Form Coordinates
Form coordinates are synonymous with the term window coordinates and refer to an entire
form or window, including the caption bar and borders. Delphi 5 doesn’t provide a DC to the
form’s drawing area through a form’s property, but you can obtain one by using the Win32 API
function GetWindowDC(), as follows:
MyDC := GetWindowDC(Form1.Handle);
This function returns the DC for the window handle passed to it.
NOTE
You can use a TCanvas object to encapsulate the device contexts obtained from the
calls to GetDC() and GetWindowDC(). This enables you to use the TCanvas methods
against those device contexts. You just need to create a TCanvas instance and then
assign the result of GetDC() or GetWindowDC() to the TCanvas.Handle property. This
11.65227_Ch08CDx 11/30/99 11:23 AM Page 97
works because the TCanvas object takes ownership of the handle you assign to it,
and it will release the DC when the canvas is freed. The following code illustrates this
technique:
var
c: TCanvas;
begin
c := TCanvas.Create;
try
c.Handle := GetDC(0);
c.TextOut(10, 10, ‘Hello World’);
finally
c.Free;
end;
end;
A form’s client-area coordinates refer to a form’s client area whose DC is the Handle property
of the form’s Canvas and whose measurements are obtained from Canvas.ClientWidth and 8
Canvas.ClientHeight.
PROGRAMMING
GRAPHICS
Coordinate Mapping
So why not just use device coordinates instead of logical coordinates when performing draw-
ing routines? Examine the following line of code:
Form1.Canvas.TextOut(0, 0, ‘Upper Left Corner of Form’);
This line places the string at the upper-left corner of the form. The coordinates (0,0) map to the
position (0,0) in the form’s device context—logical coordinates. However, the position (0,0) for
the form is completely different in device coordinates and depends on where the form is
located on your screen. If the form just happens to be located at the upper-left corner of your
screen, the form’s coordinates (0,0) may in fact map to (0,0) in device coordinates. However,
as you move the form to another location, the form’s position (0,0) will map to a completely
different location on the device.
TIP
You can obtain a point based on device coordinates from the point as it’s repre-
sented in logical coordinates, and vice versa, using the Win32 API functions
ClientToScreen() and ScreenToClient(), respectively. These are also TControl
methods. Note that this works only with screen DCs associated with a visible control.
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 98
Advanced Techniques
98
PART II
For printer or metafile DCs that are not screen based, convert logical pixels to device
pixels by using the LPtoDP() Win32 function. Also see DPtoLP() in the Win32
online help.
Underneath the call to Canvas.TextOut(), Win32 does actually use device coordinates. For
Win32 to do this, it must “map” the logical coordinates of the DC being drawn to, to device
coordinates. It does this using the mapping mode associated with the DC.
Another reason for using logical coordinates is that you might not want to use pixels to per-
form drawing routines. Perhaps you want to draw using inches or millimeters. Win32 enables
you to change the unit with which you perform your drawing routines by changing its mapping
mode, as you’ll see in a moment.
Mapping modes define two attributes for the DC: the translation that Win32 uses to convert
logical units to device units, and the orientation of the X,Y axis for the DC.
NOTE
It might not seem apparent that drawing routines, mapping modes, orientation, and
so on are associated with a DC because, in Delphi 5, you use the canvas to draw.
Remember that TCanvas is a wrapper for a DC. This becomes obvious when compar-
ing Win32 GDI routines to their equivalent Canvas routines. Here are examples:
Canvas routine: Canvas.Rectangle(0, 0, 50, 50));
GDI routine: Rectangle(ADC, 0, 0, 50, 50);
When you’re using the GDI routine, a DC is passed to the function, whereas the can-
vas’s routine uses the DC that it encapsulates.
Win32 enables to you define the mapping mode for a DC or TCanvas.Handle. In fact, Win32
defines eight mapping modes you can use. These mapping modes, along with their attributes,
are shown in Table 8.4. The sample project in the next section illustrates more about mapping
modes.
Win32 defines a few functions that enable you to change or retrieve information about the
mapping modes for a given DC. Here’s a summary of these functions:
• SetMapMode(). Sets the mapping mode for a given device context.
• GetMapMode(). Gets the mapping mode for a given device context.
• SetWindowOrgEx(). Defines an window origin (point 0,0) for a given DC.
• SetViewPortOrgEx(). Defines a viewport origin (point 0,0) for a given DC.
• SetWindowExtEx(). Defines the X,Y extents for a given window DC. These values are 8
used in conjunction with the viewport X,Y extents to perform translation from logical
PROGRAMMING
units to device units.
GRAPHICS
• SetViewPortExtEx(). Defines the X,Y extents for a given viewport DC. These values
are used in conjunction with the window X,Y extents to perform translation from logical
units to device units.
Notice that these functions contain either the word Window or ViewPort. The window or view-
port is simply a means by which Win32 GDI can perform the translation from logical to device
units. The functions with Window refer to the logical coordinate system, whereas those with
ViewPort refer to the device coordinates system. With the exception of the MM_ANISOTROPIC
and MM_ISOTROPIC mapping modes, you don’t have to worry about this much. In fact, Win32
uses the MM_TEXT mapping mode by default.
NOTE
MM_TEXT is the default mapping mode, and it maps logical coordinates 1:1 with
device coordinates. So, you’re always using device coordinates on all DCs, unless you
change the mapping mode. There are some API functions where this is significant:
Font heights, for example, are always specified in device pixels, not logical pixels.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 100
Advanced Techniques
100
PART II
As an example of drawing a 1-inch rectangle to the form, you first change the mapping mode
for Form1.Canvas.Handle to MM_HIENGLISH or MM_LOENGLISH:
SetMapMode(Canvas.Handle, MM_LOENGLISH);
Then you draw the rectangle using the appropriate units of measurement for a 1-inch rectangle.
Because MM_LOENGLISH uses 1⁄100 inch, you simply pass the value 100, as follows (this will be
illustrated further in a later example):
Canvas.Rectangle(0, 0, 100, 100);
Because MM_TEXT uses pixels as its unit of measurement, you can use the Win32 API function
GetDeviceCaps() to retrieve the information you need to perform translation from pixels to
inches or millimeters. Then you can do your own calculations if you want. This is demon-
strated in Chapter 10, “Printing in Delphi 5.” Mapping modes are a way to let Win32 do the
work for you. Note, however, that you’ll most likely never be able to get exact measurements
for screen displays. There are a few reasons for this: Windows cannot record the display size of
the screen—it must guess. Also, Windows typically inflates display scales to improve text read-
ability on relatively chunky monitors. So, for example, a 10-point font on a screen is about as
tall as a 12- to 14-point font on paper.
Likewise, these lines of code mean that five logical units require 10 device units:
SetWindowExtEx(Canvas.Handle, 5, 5, nil)
SetViewportExtEx(Canvas.Handle, 10, 10, nil);
Notice that this is exactly the same as the previous example. Both have the same effect of hav-
ing a 1:2 ratio of logical to device units. Here’s an example of how this may be used to change
the units for a form:
11.65227_Ch08CDx 11/30/99 11:23 AM Page 101
NOTE
Changing the mapping mode for a device context represented by a VCL canvas is not
“sticky,” which means that it may revert back to its original mode. Generally, the
map mode must be set within the handler doing the actual drawing.
This enables to you work with a form whose client width and height are 500×500 units (not
pixels) despite any resizing of the form.
The SetWindowOrgEx() and SetViewPortOrgEx() functions enable you to relocate the origin
or position (0,0), which, by default, is at the upper-left corner of a form’s client area in the
MM_TEXT mapping mode. Typically, you just modify the viewport origin. For example, the fol-
lowing line sets up a four-quadrant coordinate system like the one illustrated in Figure 8.13:
SetViewportOrgEx(Canvas.Handle, ClientWidth div 2, ClientHeight div 2, nil);
8
–y
PROGRAMMING
GRAPHICS
–x +x
+y
FIGURE 8.13
A four-quadrant coordinate system.
Notice that we pass a nil value as the last parameter in the SetWindowOrgEx(),
SetViewPortOrgEx(), SetWindowExtEx(), and SetViewPortExtEx() functions. The
SetWindowOrgEx() and SetViewPortOrgEx() functions take a TPoint variable that gets
assigned the last origin value so that you can restore the origin for the DC, if necessary. The
SetWindowExtEx() and SetViewPortExtEx() functions take a TSize structure to store the orig-
inal extents for the DC for the same reason.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 102
Advanced Techniques
102
PART II
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Menus, DB, DBCGrids, DBTables;
type
TMainForm = class(TForm)
mmMain: TMainMenu;
mmiMappingMode: TMenuItem;
mmiMM_ISOTROPIC: TMenuItem;
mmiMM_ANSITROPIC: TMenuItem;
mmiMM_LOENGLISH: TMenuItem;
mmiMM_HIINGLISH: TMenuItem;
mmiMM_LOMETRIC: TMenuItem;
mmiMM_HIMETRIC: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure mmiMM_ISOTROPICClick(Sender: TObject);
procedure mmiMM_ANSITROPICClick(Sender: TObject);
procedure mmiMM_LOENGLISHClick(Sender: TObject);
procedure mmiMM_HIINGLISHClick(Sender: TObject);
procedure mmiMM_LOMETRICClick(Sender: TObject);
procedure mmiMM_HIMETRICClick(Sender: TObject);
public
MappingMode: Integer;
procedure ClearCanvas;
procedure DrawMapMode(Sender: TObject);
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
procedure TMainForm.ClearCanvas;
begin
11.65227_Ch08CDx 11/30/99 11:23 AM Page 103
with Canvas do
begin
Brush.Style := bsSolid;
Brush.Color := clWhite;
FillRect(ClipRect);
end;
end;
// Set mapping mode to MM_LOENGLISH and save the previous mapping mode
PrevMapMode := SetMapMode(Canvas.Handle, MappingMode);
try
// Set the viewport org to left, bottom
SetViewPortOrgEx(Canvas.Handle, 0, ClientHeight, nil);
{ Draw some shapes to illustrate drawing shapes with different
mapping modes specified by MappingMode }
8
Canvas.Rectangle(0, 0, 200, 200);
PROGRAMMING
Canvas.Rectangle(200, 200, 400, 400);
GRAPHICS
Canvas.Ellipse(200, 200, 400, 400);
Canvas.MoveTo(0, 0);
Canvas.LineTo(400, 400);
Canvas.MoveTo(0, 200);
Canvas.LineTo(200, 0);
finally
// Restore previous mapping mode
SetMapMode(Canvas.Handle, PrevMapMode);
end;
end;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 104
Advanced Techniques
104
PART II
PROGRAMMING
begin
GRAPHICS
MappingMode := MM_LOENGLISH;
DrawMapMode(Sender);
end;
end.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 106
Advanced Techniques
106
PART II
The main form’s field MappingMode is used to hold the current mapping mode that’s initialized in
the FormCreate() method to MM_TEXT. This variable gets set whenever the MMLOENGLISH1Click(),
MMHIENGLISH1Click(), MMLOMETRIC1Click(), and MMHIMETRIC1Click() methods are invoked
from their respective menus. These methods then call the method DrawMapMode(), which sets the
main form’s mapping mode to that specified by MappingMode. It then draws some shapes and
lines using constant values to specify their sizes. When different mapping modes are used when
drawing the shapes, they’ll be sized differently on the form because the measurements used are
used in the context of the specified mapping mode. Figures 8.14 and 8.15 illustrate
DrawMapMode()’s output for the MM_LOENGLISH and MM_LOMETRIC mapping modes.
FIGURE 8.14
DrawMapMode() output using MM_LOENGLISH mapping mode.
FIGURE 8.15
DrawMapMode() output using MM_LOMETRIC mapping mode.
The mmiMM_ISOTROPICClick() method illustrates drawing with the form’s canvas in the
MM_ISOTROPIC mode. This method first sets the mapping mode and then sets the canvas’s view-
port extent to that of the form’s client area. The origin is then set to the center of the form’s
client area, which allows all four quadrants of the coordinate system to be viewed.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 107
The method then draws a rectangle in each plane and an ellipse in the center of the client area.
Notice how you can use the same values in the parameters passed to Canvas.Rectangle() yet
draw to different areas of the canvas. This is accomplished by passing negative values to the X
parameter, Y parameter, or both parameters passed to SetViewPortExt().
The mmiMM_ANISOTROPICClick() method performs the same operations except it uses the
MM_ANISOTROPIC mode. The purpose of showing both is to illustrate the principle difference
between the MM_ISOTROPIC and MM_ANISOTROPIC mapping modes.
Using the MM_ISOTROPIC mode, Win32 ensures that the two axes use the same physical size
and makes the necessary adjustments to see this is the case. The MM_ANISOTROPIC mode, how-
ever, uses physical dimensions that might not be equal. Figures 8.16 and 8.17 illustrate this
more clearly. You can see that the MM_ISOTROPIC mode ensures equality with the two axes,
whereas the same code using the MM_ANISOTROPIC mode does not ensure equality. In fact, the
MM_ISOTROPIC mode further guarantees that the square logical coordinates will be mapped to
device coordinates such that squareness will be preserved, even if the device coordinates sys-
tem is not square.
PROGRAMMING
GRAPHICS
FIGURE 8.16
MM_ISOTROPIC mapping mode output.
FIGURE 8.17
MM_ANISOTROPIC mapping mode output.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 108
Advanced Techniques
108
PART II
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Buttons, ExtCtrls, ColorGrd, StdCtrls, Menus,
ComCtrls;
const
crMove = 1;
type
TMainForm = class(TForm)
sbxMain: TScrollBox;
imgDrawingPad: TImage;
pnlToolBar: TPanel;
sbLine: TSpeedButton;
sbRectangle: TSpeedButton;
sbEllipse: TSpeedButton;
sbRoundRect: TSpeedButton;
pnlColors: TPanel;
cgDrawingColors: TColorGrid;
pnlFgBgBorder: TPanel;
pnlFgBgInner: TPanel;
Bevel1: TBevel;
mmMain: TMainMenu;
mmiFile: TMenuItem;
mmiExit: TMenuItem;
N2: TMenuItem;
mmiSaveAs: TMenuItem;
mmiSaveFile: TMenuItem;
mmiOpenFile: TMenuItem;
mmiNewFile: TMenuItem;
mmiEdit: TMenuItem;
11.65227_Ch08CDx 11/30/99 11:23 AM Page 109
mmiPaste: TMenuItem;
mmiCopy: TMenuItem;
mmiCut: TMenuItem;
sbRectSelect: TSpeedButton;
SaveDialog: TSaveDialog;
OpenDialog: TOpenDialog;
stbMain: TStatusBar;
pbPasteBox: TPaintBox;
sbFreeForm: TSpeedButton;
RgGrpFillOptions: TRadioGroup;
cbxBorder: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure sbLineClick(Sender: TObject);
procedure imgDrawingPadMouseDown(Sender: TObject; Button:
TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure imgDrawingPadMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
procedure imgDrawingPadMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure cgDrawingColorsChange(Sender: TObject);
procedure mmiExitClick(Sender: TObject);
procedure mmiSaveFileClick(Sender: TObject);
8
procedure mmiSaveAsClick(Sender: TObject);
PROGRAMMING
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
GRAPHICS
procedure mmiNewFileClick(Sender: TObject);
procedure mmiOpenFileClick(Sender: TObject);
procedure mmiEditClick(Sender: TObject);
procedure mmiCutClick(Sender: TObject);
procedure mmiCopyClick(Sender: TObject);
procedure mmiPasteClick(Sender: TObject);
procedure pbPasteBoxMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pbPasteBoxMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure pbPasteBoxMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pbPasteBoxPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure RgGrpFillOptionsClick(Sender: TObject);
public
{ Public declarations }
MouseOrg: TPoint; // Stores mouse information
NextPoint: TPoint; // Stores mouse information
Drawing: Boolean; // Drawing is being performed flag
DrawType: TDrawType; // Holds the draw type information: TDrawType
FillSelected, // Fill shapes flag
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 110
Advanced Techniques
110
PART II
var
MainForm: TMainForm;
implementation
uses ClipBrd, Math;
{$R *.DFM}
FillSelected := False;
BorderSelected := True;
Modified := False;
FileName := ‘’;
Pasted := False;
pbPasteBox.Enabled := False;
PROGRAMMING
Picture.Graphic.Height := 400;
GRAPHICS
end;
// Now create a bitmap image to hold pasted data
PasteBitmap := TBitmap.Create;
pbPasteBox.BringToFront;
{ Add the form to the Windows clipboard viewer chain. Save the handle
of the next window in the chain so that it may be restored by the
ChangeClipboardChange() Win32 API function in this form’s
FormDestroy() method. }
OldClipViewHwnd := SetClipBoardViewer(Handle);
end;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 112
Advanced Techniques
112
PART II
case DrawType of
dtLineDraw:
begin
MoveTo(TL.X, TL.Y);
LineTo(BR.X, BR.Y);
end;
dtRectangle:
Rectangle(TL.X, TL.Y, BR.X, BR.Y);
dtEllipse:
Ellipse(TL.X, TL.Y, BR.X, BR.Y);
dtRoundRect:
RoundRect(TL.X, TL.Y, BR.X, BR.Y,
(TL.X - BR.X) div 2, (TL.Y - BR.Y) div 2);
dtClipRect:
Rectangle(TL.X, TL.Y, BR.X, BR.Y);
end;
end;
end;
procedure TMainForm.CopyPasteBoxToImage;
{ This method copies the image pasted from the Windows clipboard onto
imgDrawingPad. It first erases any bounding rectangle drawn by PaintBox
component, pbPasteBox. It then copies the data from pbPasteBox onto
imgDrawingPad at the location where pbPasteBox has been dragged
over imgDrawingPad. The reason we don’t copy the contents of
pbPasteBox’s canvas and use PasteBitmap’s canvas instead, is because
when a portion of pbPasteBox is dragged out of the viewable area,
Windows does not paint the portion pbPasteBox not visible. Therefore,
it is necessary to the pasted bitmap from the off-screen bitmap }
var
11.65227_Ch08CDx 11/30/99 11:23 AM Page 113
PROGRAMMING
Modified := True;
GRAPHICS
// Erase the clipping rectangle if one has been drawn
if (DrawType = dtClipRect) and EraseClipRect then
DrawToImage(MouseOrg, NextPoint, pmNotXOR)
else if (DrawType = dtClipRect) then
EraseClipRect := True; // Re-enable cliprect erasing
Drawing := True;
// Save the mouse information
MouseOrg := Point(X, Y);
NextPoint := MouseOrg;
LastDot := NextPoint; // Lastdot is updated as the mouse moves
imgDrawingPad.Canvas.MoveTo(X, Y);
end;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 114
Advanced Techniques
114
PART II
// Now make sure the dtClipRect style doesn’t erase previous drawings
if DrawType = dtClipRect then begin
EraseClipRect := False;
end;
// Set the drawing style
SetDrawingStyle;
end;
procedure TMainForm.SetDrawingStyle;
{ This method sets the various drawing styles based on the selections
8
on the pnlFillStyle TPanel for Fill and Border styles }
PROGRAMMING
begin
GRAPHICS
with imgDrawingPad do
begin
if DrawType = dtClipRect then
begin
Canvas.Pen.Style := psDot;
Canvas.Brush.Style := bsClear;
Canvas.Pen.Color := clBlack;
end
if BorderSelected then
Canvas.Pen.Style := psSolid
else
Canvas.Pen.Style := psClear;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 116
Advanced Techniques
116
PART II
case Rslt of
mrYes: mmiSaveFileClick(nil);
mrNo: ; // no need to do anything.
mrCancel: Exit;
end
end;
CanClose := True; // Allow use to close application
end;
PROGRAMMING
end
GRAPHICS
end;
if OpenDialog.Execute then
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 118
Advanced Techniques
118
PART II
imgDrawingPad.Picture.LoadFromFile(OpenDialog.FileName);
FileName := OpenDialog.FileName;
stbMain.Panels[0].Text := FileName;
Modified := false;
end;
end;
CopyBitMap: TBitmap;
DestRect, SrcRect: TRect;
OldBrushColor: TColor;
begin
CopyBitMap := TBitMap.Create;
try
{ Set CopyBitmap’s size based on the coordinates of the
bounding rectangle }
CopyBitMap.Width := Abs(NextPoint.X - MouseOrg.X);
CopyBitMap.Height := Abs(NextPoint.Y - MouseOrg.Y);
DestRect := Rect(0, 0, CopyBitMap.Width, CopyBitmap.Height);
SrcRect := Rect(Min(MouseOrg.X, NextPoint.X)+1,
Min(MouseOrg.Y, NextPoint.Y)+1,
Max(MouseOrg.X, NextPoint.X)-1,
Max(MouseOrg.Y, NextPoint.Y)-1);
{ Copy the portion of the main image surrounded by the bounding
rectangle to the Windows clipboard }
CopyBitMap.Canvas.CopyRect(DestRect, imgDrawingPad.Canvas, SrcRect);
{ Previous versions of Delphi required the bitmap’s Handle property
to be touched for the bitmap to be made available. This was due to
Delphi’s caching of bitmapped images. The step below may not be
required. }
8
CopyBitMap.Handle;
PROGRAMMING
// Assign the image to the clipboard.
GRAPHICS
ClipBoard.Assign(CopyBitMap);
{ If cut was specified the erase the portion of the main image
surrounded by the bounding Rectangle }
if Cut then
with imgDrawingPad.Canvas do
begin
OldBrushColor := Brush.Color;
Brush.Color := clWhite;
try
FillRect(SrcRect);
finally
Brush.Color := OldBrushColor;
end;
end;
finally
CopyBitMap.Free;
end;
end;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 120
Advanced Techniques
120
PART II
pbPasteBox.Enabled := True;
if DrawType = dtClipRect then
begin
DrawToImage(MouseOrg, NextPoint, pmNotXOR);
EraseClipRect := False;
end;
pbPasteBox.Visible := True;
pbPasteBox.Invalidate;
end;
begin
PBoxMoving := True;
Screen.Cursor := crMove;
PBoxMouseOrg := Point(X, Y);
end
else
PBoxMoving := False;
end;
PROGRAMMING
Shift: TShiftState; X, Y: Integer);
GRAPHICS
begin
{ This method disables moving of pbPasteBox when the user lifts the left
mouse button }
if PBoxMoving then
begin
PBoxMoving := False;
Screen.Cursor := crDefault;
end;
pbPasteBox.Refresh; // Redraw the pbPasteBox.
end;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 122
Advanced Techniques
122
PART II
end.
FIGURE 8.18
The main form for the paint program.
NOTE
8
Notice that a TImage component is used as a drawing surface for the paint program.
PROGRAMMING
Keep in mind that this can only be the case if the image uses a TBitmap object.
GRAPHICS
The main form contains a main image component, imgDrawingPad, which is placed on a
TScrollBox component. imgDrawingPad is where the user performs drawing. The selected
speed button on the form’s toolbar specifies the type of drawing that the user performs.
The user can draw lines, rectangles, ellipses, and rounded rectangles as well as perform free-
form drawing. Additionally, a portion of the main image can be selected and copied to the
Windows Clipboard so that it can be pasted into another application that can handle bitmap
data. Likewise, the paint program can accept bitmap data from the Windows Clipboard.
TPanel Techniques
The fill style and border type are specified by the Fill Options radio group. The fill and border
colors are set using the color grid in the ColorPanel shown in Figure 8.18.
Advanced Techniques
124
PART II
Bitmap Copying
Bitmap copy operations are performed in the CopyCut(), pbPasteBoxPaint(), and
CopyPasteBoxToImage() methods. The CopyCut() method copies a portion of the main image
selected by a bounding rectangle to the Clipboard and then erases the bounded area if the Cut
parameter passed to it is True. Otherwise, it leaves the area intact.
PbPasteBoxPaint() copies the contents of the offscreen bitmap to pbPasteBox.Canvas but
only when pbPasteBox is not being moved. This helps reduce flicker as the user moves
pbPasteBox.
CopyPasteBoxToImage() copies the contents of the offscreen bitmap to the main image
imgDrawingPad at the location specified by pbPasteBox.
interface
11.65227_Ch08CDx 11/30/99 11:23 AM Page 125
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Menus, Stdctrls, AppEvnts;
type
TSprite = class
private
FWidth: integer;
FHeight: integer;
FLeft: integer;
FTop: integer;
FAndImage, FOrImage: TBitMap;
public
property Top: Integer read FTop write FTop;
property Left: Integer read FLeft write FLeft;
property Width: Integer read FWidth write FWidth;
property Height: Integer read FHeight write FHeight;
constructor Create;
destructor Destroy; override;
8
end;
PROGRAMMING
GRAPHICS
TMainForm = class(TForm)
mmMain: TMainMenu;
mmiFile: TMenuItem;
mmiSlower: TMenuItem;
mmiFaster: TMenuItem;
N1: TMenuItem;
mmiExit: TMenuItem;
appevMain: TApplicationEvents;
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure mmiExitClick(Sender: TObject);
procedure mmiSlowerClick(Sender: TObject);
procedure mmiFasterClick(Sender: TObject);
procedure appevMainIdle(Sender: TObject; var Done: Boolean);
private
BackGnd1, BackGnd2: TBitMap;
Sprite: TSprite;
GoLeft,GoRight,GoUp,GoDown: boolean;
FSpeed, FSpeedIndicator: Integer;
procedure DrawSprite;
end;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 126
Advanced Techniques
126
PART II
BackGround = ‘BACK2.BMP’;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
constructor TSprite.Create;
begin
inherited Create;
{ Create the bitmaps to hold the sprite images that will
be used for performing the AND/OR operation to create animation }
FAndImage := TBitMap.Create;
FAndImage.LoadFromResourceName(hInstance, ‘AND’);
FOrImage := TBitMap.Create;
FOrImage.LoadFromResourceName(hInstance, ‘OR’);
Left := 0;
Top := 0;
Height := FAndImage.Height;
Width := FAndImage.Width;
end;
destructor TSprite.Destroy;
begin
FAndImage.Free;
FOrImage.Free;
end;
FSpeed := 0;
FSpeedIndicator := 0;
PROGRAMMING
ClientHeight := BackGnd1.Height;
GRAPHICS
end;
procedure TMainForm.DrawSprite;
var
OldBounds: TRect;
begin
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 128
Advanced Techniques
128
PART II
if GoDown then
if (Top + Height) < self.ClientHeight then
Top := Top + 1
else begin
GoDown := false;
GoUp := true;
end;
if GoUp then
if Top > 0 then
Top := Top - 1
else begin
GoUp := false;
GoDown := true;
end;
if GoRight then
if (Left + Width) < self.ClientWidth then
Left := Left + 1
else begin
GoRight := false;
GoLeft := true;
end;
end;
{ Now draw the sprite onto the off-screen bitmap. By performing the
drawing in an off-screen bitmap, the flicker is eliminated. }
with Sprite do
begin
{ Now create a black hole where the sprite first existed by And-ing
the FAndImage onto BackGnd2 }
BitBlt(BackGnd2.Canvas.Handle, Left, Top, Width, Height,
FAndImage.Canvas.Handle, 0, 0, SrcAnd);
// Now fill in the black hole with the sprites original colors
BitBlt(BackGnd2.Canvas.Handle, Left, Top, Width, Height,
FOrImage.Canvas.Handle, 0, 0, SrcPaint);
end;
end;
8
PROGRAMMING
procedure TMainForm.FormPaint(Sender: TObject);
GRAPHICS
begin
// Draw the background image whenever the form gets painted
BitBlt(Canvas.Handle, 0, 0, ClientWidth, ClientHeight,
BackGnd1.Canvas.Handle, 0, 0, SrcCopy);
end;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 130
Advanced Techniques
130
PART II
Done := False;
end;
end.
The animation project consists of a background image on which a sprite, a flying saucer, is
drawn and moved about the background’s client area. The background is represented by a
bitmap consisting of scattered stars (see Figure 8.19).
FIGURE 8.19
The background of the animation project.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 131
The sprite is made up of two 64×32 bitmaps. More on these bitmaps later; for now, we’ll dis-
cuss what goes on in the source code.
The unit defines a TSprite class. TSprite contains the fields that hold the sprite’s location on
the background image and two TBitmap objects to hold each of the sprite bitmaps. The
TSprite.Create constructor creates both TBitmap instances and loads them with the actual
bitmaps. Both the sprite bitmaps and the background bitmap are kept in a resource file that you
link to the project by including the following statement in the main unit:
{$R SPRITES.RES }
After the bitmap is loaded, the sprite’s boundaries are set. The TSprite.Done destructor frees
both bitmap instances.
The main form contains two TBitmap objects, a TSprite object, and direction indicators to
specify the direction of the sprite’s motion. Additionally, the main form defines another
method, DrawSprite(), which has the sprite-drawing functionality. The TApplicationEvents
component is a new Delphi 5 component that allows you to hook into the Application-level
events. Prior to Delphi 5, you had to do this by adding Application-level events at runtime.
Now, with this component, you can do all event management for TApplication at design time.
We will use this component to provide an OnIdle event for the TApplication object.
8
Note that two private variables are used to control the speed of the animation: FSpeed and
PROGRAMMING
FSpeedIndicator. These are used in the DrawSprite() method for slowing down the anima-
GRAPHICS
tion on faster machines.
The FormCreate() event handler creates both TBitmap instances and loads each with the same
background bitmap. (The reason you use two bitmaps will be discussed in a moment.) It then
creates a TSprite instance, and sets the direction indicators. Finally FormCreate() resizes the
form to the background image’s size.
The FormPaint() method paints the BackGnd1 to its canvas, and the FormDestroy() frees the
TBitmap and TSprite instances.
The appevMainIdle() method calls DrawSprite(), which moves and draws the sprite on the
background. The bulk of the work is done in the DrawSprite() method.appevMainIdle() will
be invoked whenever the application is in an idle state. That is, whenever there are no actions
from the user for the application to respond to.
The DrawSprite() method repositions the sprite on the background image. A series of steps is
required to erase the old sprite on the background and then draw it at its new location while
preserving the background colors around the actual sprite image. Additionally, DrawSprite()
must perform these steps without producing flickering while the sprite is moving.
To accomplish this, drawing is performed on the offscreen bitmap, BackGnd2. BackGnd2 and
BackGnd1 are exact copies of the background image. However, BackGnd1 is never modified, so
it’s a clean copy of the background. When drawing is complete on BackGnd2, the modified area
of BackGnd2 is copied to the form’s canvas. This allows for only one BitBlt() operation to the
11.65227_Ch08CDx 11/30/99 11:23 AM Page 132
Advanced Techniques
132
PART II
form’s canvas to both erase and draw the sprite at its new location. The drawing operations per-
formed on BackGnd2 are as follows.
First, a rectangular region is copied from BackGnd1 to BackGnd2 over the area occupied by the
sprite. This effectively erases the sprite from BackGnd2. Then the FAndImage bitmap is copied
to BackGnd2 at its new location using the bitwise AND operation. This effectively creates a black
hole in BackGnd2 where the sprite exists and still preserves the colors on BackGnd2 surrounding
the sprite. Figure 8.20 shows FAndImage.
In Figure 8.20, the sprite is represented by black pixels, and the rest of the image surrounding it
consists of white pixels. The color black has a value of 0, and the color white has the value of 1.
Tables 8.5, and 8.6 show the results of performing the AND operation with black and white colors.
TABLE 8.6 AND Operation with White Color<$AND operation; with white color>
These tables show how performing the AND operation results in blacking out the area where the
sprite exists on BackGnd2. In Table 8.5, Value represents a pixel color. If a pixel on BackGnd2
contains some arbitrary color, combining this color with the color black using the AND operator
results in that pixel becoming black. Combining this color with the color white using the AND
operator results in the color being the same as the arbitrary color, as shown in Table 8.6.
Because the color surrounding the sprite in FAndImage is white, the pixels on BackGnd2 where
this portion of FAndImage is copied retain their colors.
After copying FAndImage to BackGnd2, FOrImage must be copied to the same location on
BackGnd2 to fill in the black hole created by FAndImage with the actual sprite colors. FOrImage
also has a rectangle surrounding the actual sprite image. Again, you’re faced with getting the
sprite colors to BackGnd2 while preserving BackGnd2’s colors surrounding the sprite. This is
accomplished by combining FOrImage with BackGnd2 using the OR operation. FOrImage is
shown in Figure 8.21.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 133
FIGURE 8.20
FAndImage for a sprite.
PROGRAMMING
GRAPHICS
FIGURE 8.21
FOrImage.
Notice that the area surrounding the sprite image is black. Table 8.7 shows the results of per-
forming the OR operation on FOrImage and BackGnd2.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 134
Advanced Techniques
134
PART II
Table 8.7 shows that if BackGnd2 contains an arbitrary color, using the OR operation to combine
it with black will result in BackGnd2’s color.
Recall that all this drawing is performed on the offscreen bitmap. When the drawing is com-
plete, a single BitBlt() is made to the form’s canvas to erase and copy the sprite.
The technique shown here is a fairly common method for performing animation. You might con-
sider extending the functionality of the TSprite class to move and draw itself on a parent canvas.
Advanced Fonts
Although the VCL enables you to manipulate fonts with relative ease, it doesn’t provide the
vast font-rendering capabilities provided by the Win32 API. This section gives you a back-
ground on Win32 fonts and shows you how to manipulate them.
is a collection of characters that share design characteristics; for example, Courier is a common
typeface. A font is a collection of characters that have the same typeface and size.”
Win32 categorizes these different typefaces into five font families: Decorative, Modern,
Roman, Script, and Swiss. The distinguishing font features in these families are the font’s ser-
ifs and stroke widths.
A serif is a small line at the beginning or end of a font’s main strokes that give the font a fin-
ished appearance. A stroke is the primary line that makes up the font. Figure 8.22 illustrates
these two features.
FIGURE 8.22
Serifs and strokes.
Some of the typical fonts you’ll find in the different font families are listed in Table 8.8.
8
TABLE 8.8 Font Families and Typical Fonts
PROGRAMMING
GRAPHICS
Font Family Typical Fonts
Decorative Novelty fonts: Old English
Modern Fonts with constant strike widths that may or may not have serifs: Pica,
Elite, and Courier New
Roman Fonts with variable stroke widths and serifs: Times New Roman and New
Century SchoolBook
Script Fonts that look like handwriting: Script and Cursive
Swiss Fonts with variable stroke widths without serifs: Arial and Helvetica
A font’s size is represented in points (a point is 1⁄72 of an inch). A font’s height consists of its
ascender and descender. The ascender and descender are represented by the tmAscent and
tmDescent values as shown in Figure 8.23. Figure 8.23 shows other values essential to the
character measurement as well.
Characters reside in a character cell, an area surrounding the character that consists of white
space. When referring to character measurements, keep in mind that the measurement may
include both the character glyph (the character’s visible portion) and the character cell. Others
may refer to only one or the other.
Table 8.9 explains the meaning of the various character measurements.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 136
Advanced Techniques
136
PART II
FIGURE 8.23
Character measurement values.
FIGURE 8.24
A raster font.
PROGRAMMING
GRAPHICS
FIGURE 8.25
A vector font.
FIGURE 8.26
A TrueType font.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 138
Advanced Techniques
138
PART II
FIGURE 8.27
The main form for the font-creation project.
interface
11.65227_Ch08CDx 11/30/99 11:23 AM Page 139
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, Mask, Spin;
const
PROGRAMMING
FamilyArray: array[0..5] of byte = (FF_DONTCARE, FF_ROMAN,
GRAPHICS
FF_SWISS, FF_MODERN, FF_SCRIPT, FF_DECORATIVE);
type
TMainForm = class(TForm)
lblHeight: TLabel;
lblWidth: TLabel;
gbEffects: TGroupBox;
cbxItalic: TCheckBox;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 140
Advanced Techniques
140
PART II
var
11.65227_Ch08CDx 11/30/99 11:23 AM Page 141
MainForm: TMainForm;
implementation
uses FontInfoFrm;
{$R *.DFM}
procedure TMainForm.MakeFont;
begin
// Clear the contents of FLogFont
FillChar(FLogFont, sizeof(TLogFont), 0);
// Set the TLOGFONT’s fields
with FLogFont do
begin
lfHeight := StrToInt(seHeight.Text);
lfWidth := StrToInt(seWidth.Text);
lfEscapement :=
StrToInt(cbEscapement.Items[cbEscapement.ItemIndex]);
lfOrientation :=
StrToInt(cbOrientation.Items[cbOrientation.ItemIndex]);
lfWeight
lfItalic
:= WeightArray[cbWeight.ItemIndex];
:= ord(cbxItalic.Checked);
8
lfUnderline := ord(cbxUnderLine.Checked);
PROGRAMMING
lfStrikeOut := ord(cbxStrikeOut.Checked);
GRAPHICS
lfCharSet := CharSetArray[cbCharset.ItemIndex];
lfOutPrecision := OutPrecArray[cbOutPrec.ItemIndex];
lfClipPrecision := ClipPrecArray[cbClipPrec.ItemIndex];
lfQuality := QualityArray[rgQuality.ItemIndex];
lfPitchAndFamily := PitchArray[rgPitch.ItemIndex] or
FamilyArray[cbFamily.ItemIndex];
StrPCopy(lfFaceName, cbFontFace.Items[cbFontFace.ItemIndex]);
end;
// Retrieve the requested font
FHFont := CreateFontIndirect(FLogFont);
// Assign to the Font.Handle
pbxFont.Font.Handle := FHFont;
pbxFont.Refresh;
end;
procedure TMainForm.SetDefaults;
begin
// Set the various controls to default values for ALogFont
seHeight.Text := ‘0’;
seWidth.Text := ‘0’;
cbxItalic.Checked := false;
cbxStrikeOut.Checked := false;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 142
Advanced Techniques
142
PART II
MakeFont;
end;
PROGRAMMING
GRAPHICS
In MAINFORM.PAS, you’ll see several array definitions that will be explained shortly. For now,
notice that the form has two private variables: FLogFont and FHFont. FLogFont is of type
TLOGFONT, a record structure used to describe the font to create. FHFont is the handle to the
font that gets created. The private method MakeFont() is where you create the font by first fill-
ing the FLogFont structure with values specified from the main form’s components and then
passing that structure to CreateFontIndirect(), a Win32 GDI function that returns a font
handle to the new font. Before you go on, however, you need to understand the TLOGFONT
structure.
Advanced Techniques
144
PART II
lfUnderline: Byte;
lfStrikeOut: Byte;
lfCharSet: Byte;
lfOutPrecision: Byte;
lfClipPrecision: Byte;
lfQuality: Byte;
lfPitchAndFamily: Byte;
lfFaceName: array[0..lf_FaceSize - 1] of Char;
end;
You place values in the TLOGFONT’s fields that specify the attributes you want your font to have.
Each field represents a different type of attribute. By default, most of the fields can be set to
zero, which is what the Set Defaults button on the main form does. In this instance, Win32
chooses the attributes for the font and returns whatever it pleases. The general rule is this: The
more fields you fill in, the more you can fine-tune your font style. The following list explains
what each TLOGFONT field represents. Some of the fields may be assigned constant values that
are predefined in the WINDOWS unit. Refer to Win32 help for a detailed description of these val-
ues; we show you only the most commonly used ones here:
lfWeight This affects the font density. The WINDOWS unit defines several
constants for this field, such as FW_BOLD and FW_NORMAL. Set this
field to FW_DONTCARE to let Win32 choose a weight for you.
lfItalic Nonzero means italic; zero means nonitalic.
lfUnderline Nonzero means underlined; zero means not underlined.
lfStrikeOut Nonzero means that a line gets drawn through the font, whereas a
value of zero does not draw a line through the font.
lfCharSet Win32 defines the character sets: ANSI_CHARSET=0,
DEFAULT_CHARSET=1, SYMBOL_CHARSET=2,
SHIFTJIS_CHARSET=128, and OEM_CHARSET = 255. Use the
DEFAULT_CHARSET by default.
lfOutPrecision Specifies how Win32 should match the requested font’s size and
characteristics to an actual font. Use TT_ONLY_PRECIS to specify
only TrueType fonts. Other types are defined in the WINDOWS unit.
lfClipPrecision Specifies how Win32 clips characters outside a clipping region.
Use CLIP_DEFAULT_PRECIS to let Win32 choose.
lfQuality Defines the font’s output quality as GDI will draw it. Use
DEFAULT_QUALITY to let Win32 decide, or you may specify 8
PROOF_QUALITY or DRAFT_QUALITY.
PROGRAMMING
lfPitchAndFamily Defines the font’s pitch in the two low-order bits. Specifies the
GRAPHICS
family in the higher four high-order bits. Table 8.8 displays these
families.
lfFaceName The typeface name of the font.
The MakeFont() procedure uses the values defined in the constant section of MainForm.pas.
These array constants contain the various predefined constant values for the TLOGFONT struc-
ture. These values are placed in the same order as the choices in the main form’s TComboBox
components. For example, the choices for the font family in the CBFamily combo box are in
the same order as the values in FamilyArray. We used this technique to reduce the code
required to fill in the TLOGFONT structure. The first line in the MakeFont() function
fillChar(FLogFont, sizeof(TLogFont), 0);
clears the FLogFont structure before any values are set. When FLogFont has been set, the line
FHFont := CreateFontIndirect(FLogFont);
calls the Win32 API function CreateFontIndirect(), which accepts the TLOGFONT structure as
a parameter and returns a handle to the requested font. This handle is then set to the
TPaintBox.Font’s handle property. Delphi 5 takes care of destroying the TPaintBox’s previous
font before making the assignment. After the assignment is made, you redraw pbxFont by call-
ing its Refresh() method.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 146
Advanced Techniques
146
PART II
The SetDefaults() method initializes the TLOGFONT structure with default values. This method
is called when the main form is created and whenever the user clicks the Set Defaults button.
Experiment with the project to see the different effects you can get with fonts, as shown in
Figure 8.28.
FIGURE 8.28
A rotated font.
tmMaxCharWidth: Integer;
tmWeight: Integer;
tmItalic: Byte;
tmUnderlined: Byte;
tmStruckOut: Byte;
tmFirstChar: Byte;
tmLastChar: Byte;
tmDefaultChar: Byte;
tmBreakChar: Byte;
tmPitchAndFamily: Byte;
tmCharSet: Byte;
tmOverhang: Integer;
tmDigitizedAspectX: Integer;
tmDigitizedAspectY: Integer;
end;
The TTEXTMETRIC record’s fields contain much of the same information we’ve already dis-
cussed about fonts. For example, it shows a font’s height, average character width, and whether
the font is underlined, italicized, struck out, and so on. Refer to the Win32 API online help for
detailed information on the TTEXTMETRIC structure. Listing 8.10 shows the code for the font 8
information form.
PROGRAMMING
GRAPHICS
LISTING 8.10 Source to the Font Information Form
unit FontInfoFrm;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, ExtCtrls, StdCtrls;
type
TFontInfoForm = class(TForm)
lbFontInfo: TListBox;
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 148
Advanced Techniques
148
PART II
var
FontInfoForm: TFontInfoForm;
implementation
uses MainFrm;
{$R *.DFM}
Add(‘tmWeight: ‘+IntToStr(tmWeight));
PROGRAMMING
if (PitchTest and TMPF_VECTOR) = TMPF_VECTOR then
GRAPHICS
Add(‘tmPitchAndFamily-Pitch: Vector’);
if (PitchTest and TMPF_TRUETYPE) = TMPF_TRUETYPE then
Add(‘tmPitchAndFamily-Pitch: True type’);
if (PitchTest and TMPF_DEVICE) = TMPF_DEVICE then
Add(‘tmPitchAndFamily-Pitch: Device’);
if PitchTest = 0 then
Add(‘tmPitchAndFamily-Pitch: Unknown’);
continues
11.65227_Ch08CDx 11/30/99 11:23 AM Page 150
Advanced Techniques
150
PART II
if FamilyTest = 0 then
Add(‘tmPitchAndFamily-Family: Unknown’);
Add(‘tmCharSet: ‘+IntToStr(tmCharSet));
Add(‘tmOverhang: ‘+IntToStr(tmOverhang));
Add(‘tmDigitizedAspectX: ‘+IntToStr(tmDigitizedAspectX));
Add(‘tmDigitizedAspectY: ‘+IntToStr(tmDigitizedAspectY));
end;
end;
end.
The FormActive() method first retrieves the font’s name with the Win32 API function
GetTextFace(), which takes a device context, a buffer size, and a null-terminated character
buffer as parameters. FormActivate() then uses GetTextMetrics() to fill TxMetric, a TTEXT-
METRIC record structure, for the selected font. The event handler then adds the values in
TxMetric to the list box as strings. For the tmPitchAndFamily value, you mask out the high- or
low-order bit, depending on the value you’re testing for, and add the appropriate values to the
list box. Figure 8.29 shows FontInfoForm displaying information about a font.
FIGURE 8.29
The font information form.
11.65227_Ch08CDx 11/30/99 11:23 AM Page 151
Summary
This chapter presented you with a lot of information about the Win32 Graphics Device
Interface. We discussed Delphi 5’s TCanvas, its properties, and its drawing methods. We also
discussed Delphi 5’s representation of images with its TImage component as well as mapping
modes and Win32 coordinates systems. You saw how you can use graphics programming tech-
niques to build a paint program and perform simple animation. Finally, we discussed fonts—
how to create them and how to display information about them. One of the nice things about
the GDI is that working with it can be a lot of fun. Entire books have been written on this sub-
ject alone. Take some time to experiment with the drawing routines, create your own fonts, or
just fool around with the mapping modes to see what type of effects you can get.
PROGRAMMING
GRAPHICS
11.65227_Ch08CDx 11/30/99 11:23 AM Page 152