Working with graphics in Delphi
Many objects have a Canvas property: shapes are drawn on it. For drawing it is convenient to use the Image object from the Additional tab, because a shape drawn on it is not lost when the window is covered and shown again (a shape drawn directly on Form1.Canvas can disappear when the window is covered by another). Coordinates are counted from the upper left corner of the canvas: x – to the right, y – down. Rectangle(x1, y1, x2, y2) draws a rectangle and Ellipse(x1, y1, x2, y2) an ellipse inscribed in that rectangle; an ellipse in a square is a circle. MoveTo(x, y) moves the pen to a point and LineTo(x, y) draws a segment from the current point to the given point. The Pen (Color, Width, Style) draws lines and the Brush (Color, Style) fills the inner area. A colour is given with cl names (clRed, clBlue, clYellow) or with RGB(red, green, blue), each value from 0 to 255, so there are 256·256·256 = 16777216 colours. One dot can be coloured with Canvas.Pixels[x, y] := RGB(255, 0, 0); In Lazarus use RGBToColor(r, g, b) instead of RGB.
| Colour | RGB |
|---|---|
| yellow | (255, 255, 0) |
| blue | (0, 0, 255) |
| black | (0, 0, 0) |
| white | (255, 255, 255) |
A pupil drew a school map on squared paper and described the library with just two corners: from 2 across and 3 down to 6 across and 5 down. With these corner numbers anyone can draw the same rectangle. A computer also draws a shape from its corner coordinates, counting from the top left corner.
Game programmers, graphic designers and map makers define shapes exactly with coordinates.
On squared paper choose a rectangle by the coordinates of two corners and give a friend only those numbers to see if they can draw the same rectangle.
1procedure TForm1.Button1Click(Sender: TObject); 2begin 3 Image1.Canvas.Rectangle(40, 80, 140, 160); 4 Image1.Canvas.MoveTo(40, 80); 5 Image1.Canvas.LineTo(90, 40); 6 Image1.Canvas.LineTo(140, 80); 7end;
“House and sun”: a pair draws a house, a door and a sun with their own coordinates; they calculate the width and height of the wall in advance and compare them with the sizes in the picture.