In this chapter, you'll see how to implement several simple effects like converting an image to grayscale and inverting colors using the TCanvas.Pixels and TBitmap.ScanLine properties. You'll also learn how to create an extremely useful TImageList descendant that can generate disabled glyphs at run time, thus saving development time since you won't need to find or create disabled glyphs that match the normal glyph. Even better, using this component reduces the size of the executable significantly since you won't have to add disabled glyphs to the form at design time.
Before we can start writing the graphics related code, we have to create a new VCL Forms application and write a small amount of utility code for opening and displaying bitmaps on the form. The following figure shows the test application at run time.
Figure 28-1: The test application
To enable us to easily test various effects, this application does the following:
Creates a TBitmap instance in the OnCreate event handler
Releases the TBitmap instance from memory in the OnDestroy event handler
Uses the TOpenDialog component to enable us to select a bitmap
Draws the selected bitmap in the OnPaint event handler
Listing 28-1 shows everything required for the subsequent graphics code.
Listing 28-1: The utility code
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus; type TMainForm = class(TForm) private { Private declarations } FImage: TBitmap; public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.FileExitClick(Sender: TObject); begin Close; end; procedure TMainForm.FormCreate(Sender: TObject); begin FImage := TBitmap.Create; { if your resolution is high enough, resize the form to display the entire 800x600 flower.bmp image that comes with this example } if Screen.Width >= 1024 then begin ClientWidth := 800; ClientHeight := 600; end; end; procedure TMainForm.FormDestroy(Sender: TObject); begin FImage.Free; end; procedure TMainForm.FormPaint(Sender: TObject); begin if OpenDialog.FileName <> '' then Canvas.Draw(0, 0, FImage); end; procedure TMainForm.FileOpenClick(Sender: TObject); begin if OpenDialog.Execute then begin FImage.LoadFromFile(OpenDialog.FileName); Invalidate; { Display the image } end; end; end.