Drawing on a Canvas
A canvas is a property of several objects such as a form, a bitmap and a printer. The canvas class has many methods for drawing, some of which we demonstrate in program CanvasDemo. You can use similar graphics code in the normal Delphi and Lazarus form-based applications in which you add components to the form using a graphical user interface (GUI).
The pen has properties for the colour, style and width of lines and outlines. The brush has properties for the colour and style of the fill. We summarise common drawing methods below.
- Draw a rectangle on a canvas by calling its Rectangle method, passing as arguments the top left and bottom right coordinates of the rectangle.
- Draw an ellipse by calling the Ellipse method, passing the top left and bottom right coordinates of the bounding rectangle.
- Draw a rounded rectangle by calling the RoundRect method, passing the coordinates of the bounding rectangle followed by the width and height of the ellipse used to draw the rounded corners.
- Draw an arc of an ellipse by calling the Arc method, passing the coordinates of the bounding rectangle followed by the coordinates of two points (x1, y1) and (x2, y2). The starting point of the arc is the intersection of the ellipse with a line from the centre of the ellipse to (x1, y1). The arc runs anticlockwise round the perimeter of the ellipse until it meets the line from the centre of the ellipse to (x2, y2).
- The Pie method to draw a pie-shaped wedge on the canvas is similar to the Arc method. As usual, the first four parameters are the coordinates of the top left and bottom right corners of the bounding rectangle of the ellipse. The other four parameters are the coordinates of two points (x1, y1) and (x2, y2). The pie slice drawn is determined by two lines radiating from the centre of the ellipse through the points (x1, y1) and (x2, y2).
- Call the Chord method to create a shape that is defined by an arc of an ellipse and a line that joins the endpoints of the arc. The first four parameters are the coordinates of the bounding rectangle of the ellipse and they are followed by the coordinates of two points. The ellipse is bisected by a line that runs between these two points.
- The parameter for the Polyline and Polygon methods is an array of TPoints, with the last point equal to the first to complete the closed shape.
- Colour a single pixel by code such as Canvas.Pixels[x, y] := clMaroon. We needed to draw several pixels to make a point sufficiently visible, and resorted to the Rectangle method.
Select the link below for the Delphi or Lazarus version of the canvas demonstration.