[Home] [Puzzles & Projects] [Delphi Techniques] [Math Topics] [Library] [Utilities]
Here's a simple program that illustrates how to draw on a canvas, save the drawing to a bitmap (or file), clear the canvas and redisplay a previously saved image. Oh, and scribble too if you want.
We'll use a TImage component to provide the canvas. Even though forms have canvas properties, drawing on them generally causes more headaches than it's worth. First, it is impossible to redraw the image when the form is redisplayed. Also the canvas covers the entire form so it's easy to draw on top of other controls ( buttons. labels, etc.), usually with undesirable results. Both of these problems disappear when we use TImage.
I placed several buttons on the form:
Retrieving the images from the listbox when the user selects and item is pretty easy - just copy the bitmap from the selected item back to the canvas, again using Copyrect.
Finally I added a scribble feature to allow user drawing on the canvas. This uses a OnMouseDown exit to set the initial drawing parameters (Pen width and color) and to set a Drawing boolean variable so that OnMouseMove will know whether a line is to be drawn. And of course, OnMouseUp exits just to reset the Drawing flag to false. I learned here that cursor refresh while drawing sometimes erases a portion of the line being drawn. The solution trick is to set the Cursor to CrNone before the line is drawn and CrDefault after.
Plenty of room to expand on this if you want -- user control of pen colors and widths, erase or undo mode, customized cursors, for starters.
Copyright © 2000-2014, Gary Darby
All rights reserved.