I've had many people ask for an example for how to create a Canvas that allows you to:
- Draw pictures within it (as objects)
- Move these objects
- Remove them
- Add labels to them
- Programmatically select one
|ObjectsInCanvas Example Project|
This example demonstrates how to do all these things. It has a large Canvas on the window with several buttons that let you add and manage the objects on the Canvas.
Use the SegmentControl to select the type of object you want to add to the Canvas and click the Add Object button. You can optionally specify text to label the object using the field below the button.
Add as many objects as you want. You can click to select an object and it will have a black border drawn around it. You can drag any object within the Canvas.
The other buttons center or remove a selected object. You can use the Select Object # button to select the object number you specify (objects are numbered starting at 0).
And there is no flickering on Windows.
About the Project
The CanvasObject class represents an object. It contains its coordinates, label text, the icon to display and other properties.
The ObjectContainerCanvas class is a subclass of Canvas that is responsible for all the drawing, moving and removing of CanvasObjects. This class has an array of CanvasObjects that it knows about. The objects in this array are drawn by the Canvas Paint event handler when appropriate.
To allow you to drag an object within the Canvas, the MouseDrag event handler is used. It knows what the currently selected CanvasObject is and as you drag the mouse, it updates the coordinates for the CanvasObject.
When the Canvas is told to redraw itself, usually through a call to Invalidate, the Paint event is called. Here each CanvasObject in the array is drawn on the screen. This is the Paint event:
If Background <> Nil Then
g.DrawPicture(Background, 0, 0)
For Each co As CanvasObject In mCanvasObjects
The Draw method draws the image for the CanvasObject at the specified coordinates and if it is selected also draws a border around it. This is the Draw method:
// Draws a object on the canvas.
g.DrawPicture(co.Image, co.Left, co.Top)
If co.Selected Then
Const kBorder = 2
// Draw selection
g.PenHeight = kBorder
g.PenWidth = kBorder
g.DrawRect(co.Left-kBorder, co.Top-kBorder, co.Width+kBorder*2, co.Height+kBorder*2)
In addition, ObjectContainerCanvas has two events that are called when an object is selected (ObjectSelected) and when an object is moved (ObjectMoved).