How to set up smartphones and PCs. Informational portal
  • home
  • Advice
  • Components for displaying graphical information. Presentation on programming in the Delphi environment on the topic: "Displaying graphic information in Delphi"

Components for displaying graphical information. Presentation on programming in the Delphi environment on the topic: "Displaying graphic information in Delphi"

LABORATORY WORK

TOPIC: « Graphics inDelphi- construction of the simplest
geometric shapes "

Summary of theory

Delphi provides the developer with three ways to display graphics:

    plotting while the program is running

    use of pre-created graphic images

    creating images using graphic components

To build graphs, special classes have been created that provide tools and methods for drawing: tools are described in three classes - Tfont, Tpen, Tbrush; drawing area and methods are provided by the Tcanvas class.

ClassTfont- sets the characteristics of the font used to display the text on the canvas. The properties of the class are described in the section "Basic properties available for most components".

ClassTpen- sets the characteristics of the pen (pencil) with which lines are drawn.

Properties class Tpen:

Color: Tcolor - line color (default is black)

Width: integer - line thickness in pixels;

Style = (psSolid, psDash, psDot, psdashDot, psClear) - defines the line style (solid, dash, dash, dash-dot, invisible)

ClassTbrush- sets the characteristics of the brush, which is used to paint over the surface of the image.

Properties class Tbrush:

Color: Tcolor - brush color (default is white)

Style- brush ornament, can take on the values:

BsSolid - solid coloring

BsClear - lack of shading

BsVertical - vertical lines

BsBdiagonal - right diagonal lines

BsDiagCross - slanting cell

BsHorisontal - horizontal lines

BsFdiagonal - left diagonal lines

BsCross - cell

ClassTcanvas- defines the surface on which the created image is placed, and the tools with which the image is created: font, pencil, brush.

By default, the entire client area of ​​the form (without the title, main menu and form scrolling lines) is used as the work area (canvas, "canvas"), but you can set aside smaller work areas inside the form using components Paintbox or Image... The origin of the canvas coordinate is the upper left corner of the work area, the width of the work area is determined by the property ClientWidth, height - by the property ClientHeight.

Properties class Tcanvas:

Canvas: Tcanvas - defines the drawing area

Brush: Tbrush - brush for filling closed shapes

Font: Tfont - font for displaying text on canvas

Pen: Tpen - pencil (pen) for drawing

PenPos: Tpoint - the current position of the invisible cursor on the canvas

Comment : type Tpoint - defined as follows:

Type Tpoint = record

Pixels: Tcolor - sets the colors of the canvas pixels, X, Y - pixel coordinates. The Pixels property is useful for plotting graphs using points of a selected color.

Basic methods of the TCanvas class

    procedure MoveTo(x, y: integer); - moves the pen without drawing a line to a point with coordinates (x, y).

    Procedure LineTo(x, y: integer); - draws a line from the current point to the point with coordinates (x, y).

Example : Draw a blue diagonal line on the shape from the upper left corner of the shape to the lower right corner.

Pen.color: = clblue;

MoveTo (0,0); LineTo (ClientWidth, ClientHeight);

    procedure Rectangle(x1, y1, x2, y2: integer); - draws a rectangle: x1, y1 - coordinates of the upper left corner; х2, у2- coordinates of the lower right corner.

Example : Draw a yellow filled 60 px square in the middle of the shape.

var Xc, Yc: integer; //

Xc: = ClientWidth div 2;

Xy: = ClientHeight div 2;

Canvas.Brush.color: = clyellow;

Canvas.rectangle (xc-30, Yc-30, xc + 30, Yc + 30);

    procedure Ellipse(x1, y1, x2, y2: integer); - draws an ellipse inscribed in a rectangle with the specified coordinates.

Example : draw an ellipse inscribed in the PaintBox component.

PaintBox1.Canvas.Pen.Width: = 4; // line width = 4 pixels

PaintBox1.Canvas.Ellipse (0,0, PaintBox1. ClientWidth, PaintBox1. ClientHeight);

    procedure Polygon(); - draws a closed polygon given by an array of coordinates.

Example : draw a filled rhombus connecting the midpoints of the sides of the shape

Var Xc, Yc: integer; // coordinates of the center of the client area of ​​the form

Xc: = ClientWidth div 2;

Xy: = ClientHeight div 2;

Canvas.Brush.Color: = Rgb (275,140,70); // Orange color shading

Canvas.Polygon ();

end;

    Procedure Arc(x1, y1, x2, y2, x3, y3, x4, y4: integer); - displays the arc of an ellipse bounded by a rectangle (x1, y1, x2, y2). The arc is displayed from a point with coordinates (x3, y3) to a point with coordinates (x4, y4) against clockwise.

Example : draw an ellipse arc connecting the middle of the top side of the component
PaintBox with the middle of its right side.

Procedure Tform1.Button1Click (Sender: Tobject);

Var X3, y3, x4, y4: Integer;

With PaintBox1 do

Canvas.Pen.Color: = clWhite;

Canvas.Pen.Width: = 3;

Canvas.rectangle (0, 0, PaintBox1.ClientWidth, PaintBox1.ClientHeight);

X3: = ClientWidth div 2;

X4: = ClientWidth;

Y4: = ClientHeight div 2;

Canvas.Pen.Color: = clMaroon;

Canvas.ARC (0, 0, PaintBox1.ClientWidth, PaintBox1.ClientHeight, x3, y3, x4, y4);

End;

    procedure Chord(x1, y1, x2, y2, x3, y3, x4, y4: integer); - draws a chord - a straight line connecting 2 points of the ellipse: a point with coordinates (x3, y3) with a point (x4, y4).

Example : substitute in the example given for the ARC method, the Chord method and get this result.

    procedure Pie(x1, y1, x2, y2, x3, y3, x4, y4: integer); - draws an ellipse segment connecting the center of the ellipse with coordinates (x3, y3) and (x4, y4).

Example : Introduce the PIE method in the example given for the ARC method and get this result.

    procedure TextOut(x, y: integer; Text: string); - outputs the string passed in the Text parameter into a rectangle, the upper left corner of which is specified by the x, y coordinates. Font characteristics are set with the Font tool.

Example : write the name of the plotted graph at the bottom of the form.

Canvas.Font.Height: = 20 ; // character height 20 pixels

Canvas.Font.Color: = clblue;

Canvas.TextOut (10, ClientHeight-24, 'graph of SIN (X) function');

Graphics components

Delphi offers a number of out-of-the-box components to enhance the user experience. These components are posted on the page Additional and System palette of components.

ComponentImage(ClassTimage) - designed to display graphic images stored in external files with extensions:

    Ico (icon, pictogram);

    Bmp (bitmap, bitmap);

    Wmf, .emf (metafile);

    Jpg, .jpeg (JPEG compressed image).

The main properties :

Autosize: boolean - if true, the component adjusts its size to the size of the loaded image; by default false.

Stretch: boolean - if true, the loaded value occupies the entire area of ​​the component; the default is false.

Canvas: Tcanvas - is used for drawing inside the component at the stage of program execution.

Picture: Tpicture-defines the picture placed in the component.

The main methods class Tpicture:

Procedure LoadFromFile(Filename: string); - loads into the component an image from a file named Filename.

Procedure SaveToFile(Filename: string); - saves the image from the component to a file named Filename.

ComponentPaintbox - defines a rectangular area to draw. The main property is Canvas, all methods of the Tcanvas class are available, it has no independent properties.

Example : draw a yellow ellipse inscribed in the PaintBox1 component.

Procedure Tform1Button1Click (sender: Tobject);

With PaintBox1.Canvas do

Brush.Color: = clyellow;

Ellipse (0,0, PaintBox1.ClientWidth, PaintBox1.ClientHeight);

end;

ComponentBitBtn raster button

The BitBtn button, unlike the standard one, can, in addition to its name (Caption), contain an image set by the property Glyph... There is a set of standard buttons BitBtn, with predefined properties (with a specific picture, label and purpose) - the type of a standard button is selected through the property Kind... Kind = (bkCustom, bkAbort, bkCancel, bkClose ...)

Task number 1

Create an application that contains on the main form two Image components and 4 buttons ("Load Image", "Build Geometric Shape", "Change Color", "Exit"), and allows you to:

a) load a user-selected graphic into the Image1 component so that the image occupies the entire area of ​​the Image component.

b) under the Image1 component display the inscription “This is a picture from a file.

(for any measurement of the dimensions and position of the componentImage1 inscription must
directly under the component).

c) draw a geometric figure inside the Image2 component: a filled ellipse segment connecting the middle of the Image component with the middle of the lower and right sides of the Image component.

(for any change in the size and position of the componentImage2 the figure must be built correctly, i.e. according to the assignment regarding the componentImage2)

d) change the color of the line drawn in Image2 at the user's request using the ColorDialog component.

Task number 2

Create an application that allows you to randomly arrange several labels in the Image component (for example, the word "Hurray!"). For implementation, use the Randomize random number generator and the Random function.

The dimensions of the Image component, the word displayed in the Image and the number of words - must be entered by the user.

Task number 3

Create an application that allows you to select the name of a geometric shape from the ListBox and draw the selected shape in the Image component. The color of the shape is selected from the RadioGroup component.

Task number 4

Divide the PaintBox1 component into 4 equal parts, paint each part in a different color, for example: blue, yellow, green, red.

Next to each corner of PaintBox1, write the coordinates of this corner (relative to the origin of the form on which the PaintBox1 component is located).

Task number 5

WITH

select the type of the drawn shape from the Radiogroup1 component, the fill color from the Radiogroup2 component and draw the selected shape in the Image component.

Task number 6

Create an application that allows the user to size the PaintBox1 component (in pixels).

Divide the PaintBox1 component into 2 equal parts, inside each part draw an ellipse painted in the color selected by the user in the ColorDialog.

Task number 7

WITH Create an application that allows you to:

select the name of a geometric shape from the ListBox and draw the selected shape in the Image component. The shape should be filled with the user-selected color in the ColorDialog component if the RadioGroup component is set to Yes.

Task number 8

Create an application that allows the user to size the PaintBox1 component (in pixels).

Divide the PaintBox1 component into 4 equal parts, inside each part draw a different geometric shape (ellipse, rhombus, triangle and rectangle). The color of each shape is selected by the user in the ColorGrid.

Task number 9

select a geometric name from the ListBox
shapes (ellipse, rhombus, rectangle) and draw
the selected shape in the Image component. Location
figures in the Image component (I quarter, II quarter,

III or IV quarter) and the fill color of the figure is selected
from the RadioGroup components.

Task number 10

Create an application that allows the user to size the PaintBox1 component (in pixels).

Provide that the side size cannot be text, cannot be a negative number, and cannot exceed the smaller size of the form.

Divide the PaintBox1 component into 4 equal parts, inside each part draw a geometric shape selected by the user in the Combobox (ellipse, rhombus, triangle and rectangle). The color of the shape, selected by the user in the ColorBox.

Task number 11

Create an application that allows you to:

Select the position of the drawing from the Radiogroup component

in the Image component of a right triangle, set
shape fill color or outline color depending on
enable checkbox buttons. Select color through
the ColorGrid component.

Task number 12

Create an application that allows the user to size the PaintBox1 component (in pixels).

Provide that the side size cannot be text, cannot be a negative number, and cannot exceed the smaller size of the form.

Divide the PaintBox1 component into 2 equal parts, inside one of the parts draw a geometric shape selected by the user in the Combobox (ellipse, rhombus, triangle and rectangle). The color of the shape, selected by the user in the ColorBox.

For example, you can change the color of a form as follows:

form1.Color: = ColorBox1.Colors;

Task number 13

Create an application that allows you to:

a) draw a square in the middle of the shape (the size of the side of the square is entered by the user). Provide that the side size cannot be text, cannot be a negative number, and cannot exceed the smaller size of the form.

b) divide the square by one diagonal or two, depending on the inclusion of the Checkbox buttons and paint each resulting triangle in a different color. The choice of color is made by the user.

Task number 14

Create an application that allows the user to size the PaintBox1 component (in pixels).

Provide that the side size cannot be text, cannot be a negative number, and cannot exceed the smaller size of the form.

Divide the PaintBox1 component into 2 equal parts, draw a diamond inside one part, and draw any triangle inside the other part. The color of the shape, selected by the user in the ColorBox.

For example, you can change the color of a form as follows:

form1.Color: = ColorBox1.Colors;

Task number 15

Create an application that allows you to:

a) set the horizontal and vertical dimensions of the Image component to be the same and equal to the number entered by the user from the keyboard;

(provide that the size of the side cannot be text, cannot be a negative number and cannot exceed the smaller size of the form)

b) divide the Image component into 4 equal squares with two blue lines;

c) inside each resulting square, draw a circle inscribed in it (let the user choose the color of the circles through the color selection dialog box).

Task number 16

Create an application that allows the user to size the PaintBox1 component (in pixels).

Provide that the side size cannot be text, cannot be a negative number, and cannot exceed the smaller size of the form.

Divide the PaintBox1 component into 9 equal parts and paint each resulting rectangle in the form of a checkerboard. The fill color is selected by the user in the ColorBox.

For example, you can change the color of a form as follows:

form1.Color: = ColorBox1.Colors;

Task number 17

Place two Image components and four buttons on the form: Line Color, Fill Color, Ok and Exit; and the Edit component.

When you click OK, a square with side X is drawn in Image1, and a right-angled triangle with equal legs, each of which has length X, is drawn in Image2.

The vertex of the triangle coincides with the origin of Image2. One of the vertices of the square coincides with the origin of Image1.

The OK button becomes available only when the line color and fill color are selected for drawing the shape.

X - selects randomly, using the Random function and the value of the X value should be displayed in the Edit component.

Task number 18

Create an application that allows the user to size the PaintBox1 component (in pixels).

Divide the PaintBox1 component into 4 equal parts, inside the part selected by the user, a filled circle should be built, the size of which is set by the user. The user chooses the fill color in the ColorBox.

For example, you can change the color of a form as follows:

form1.Color: = ColorBox1.Colors;

The Visual Component Library (VCL) Delphi provides us with the following visual components for displaying graphic information: Image (image), PaintBox (window for drawing), DrawGrid (table of figures), Chart (charts and graphs), Animate ( video clip output), as well as Form. These components have a Canvas property (discussed above) that gives access to each pixel. Of course, you don't have to draw pixel by pixel to work with graphics in Delphi, the Delphi system provides powerful tools for working with graphics.

Let's consider the above components in more detail:

Image component (image)

It is an object of the TImage class. Used to display images read from graphic files on the screen. By default, it outputs to the surface of the form images presented in * .bmp format. To display images in jpg format, it is necessary to connect the JPEG unit in the uses directive. Located in the Additional tab of the Component Palette.

After placing the Image component on the form, it takes the form of a selected rectangular area.

Figure 9 - The Image component on the form

To open a dialog for selecting the desired image, do the following using the Object Inspector. To do this, find the Picture property and click on three dots to the left of it. The Picture Editor window opens and in it we select Load, in the opened window we select the image file.

It can also be done programmatically by calling the LoadFromFile method of the Picture property:

Image1.Picture.LoadFromFile ("name_pic.jpeg");

where name_pic.jpeg is the name of the file.

Table 8 - Basic properties of the Image component

Property

Description

The image displayed in the component field

Component dimensions. If these dimensions are smaller than the artwork size, and the Strech, AutoSize, and Proportional properties are False, then a portion of the image is displayed.

Allows you to automatically scale pictures without distortion. To perform scaling, the value of the AutoSize property must be equal to False

Allows you to automatically scale (shrink or stretch) an image to fit the size of the Image component. If the size of the component is not proportional to the size of the image, then the image will be distorted

Allows you to automatically resize the component to fit the image

Allows you to determine the horizontal position of the image in the Image component field if the width of the image is less than the width of the component.

Surface to display graphics

Specifies the transparent background color of the image

Example 1: Write a program to view images using the Image component. The program must have the following capabilities:

  • · View the images in the folder;
  • · View the image in full size or in the format most suitable for the size of the window;
  • · Manage image files, as well as print, save, delete and modify images;
  • · If necessary, open the image in the editing program;

Figure 10 - The program window before it starts

Project creation:

  • 1. Create a folder for the program files and launch the Delphi integrated development environment.
  • 2. Add components to the form:

First, we will place the Image component on the form, the main component with which we will have to work. In addition to him, we need the following components:

  • · ScrollBox It is necessary when in full-size mode the image will go beyond the Image. We set its Aling property to the value alClient so that its size changes proportionally to the size of the window. And place the Image component on it;
  • · We will also add the components-dialogs SavePictureDialog and OpenPictureDialog, intended for saving and opening images. We need the first to copy the image to the selected directory, the second to call the dialog for opening a graphic file. They are located on the Dialogs page of the Component Palette. Also from this page we need the PrintDialog component, which we need to call the dialog for choosing a printer for printing.
  • Add MainMenu to add the main menu to the program and XPManifest for a more colorful design
  • · We also need to store the names of the images in the working directory somewhere. For these purposes, the ListBox component is convenient, which can be hidden when processing the Create event of Form1.
  • · To place the navigation buttons and conveniently work with them, add a Veil panel, on which we will place these buttons (Previous image, Next image, True size, Resize, Delete, Copy to, Print, Edit). SpeedButton is selected as a component for them.
  • · Add a timer to catch the "Left" (previous image), "Right" (next image) and "Del" keys (delete the image).
  • · And one more component - ProgressBar, which displays the process of loading large * .Jpg files.
  • 3. Write the code for handling the event of pressing the buttons (Previous image, Next image, True size, Resize, Delete, Copy to, Print, Edit). Write the code for handling the event of clicking on the MainMenu menu items (Exit, Open, Close, Create).
  • 4. Specify the initial settings for creating the form. Double-click the free space of the form and write the procedure code procedure TForm1.FormCreate (Sender: TObject), see the module code in Appendix 1.
  • 5. Write procedures of the following type:

procedure FindFileInFolder (path, ext: string);

This routine scans the path folder for files using the ext mask.

The complete listing of the program module code is located in Appendix 1 (Program Listing 3).

  • 1. List the capabilities of the Image component.
  • 2. What class is the Image component of?
  • 3. 3. What type of files does the Image component support by default?
  • 4. 4. List the main properties of the Image component.
  • 5. 5. What property stores the image of the Image component?

Topic :
The purpose of the laboratory work Delphi.

Students must learn to:

  • Create charts

Theoretical part

Pictogram Name Page Appointment
Image Additional
Shape Additional
DrawGrid

(table of figures)

Additional
Chart

(diagrams and graphs)

Additional
Paintbox

(drawing window)

System

Shape Brush

Image:

Chart:

Method Clear

Method Add

Method AddXY

PaintBox:

Exercise 1

Assignment 2

Assignment 3

with PaintBox1, canvas do

Brush.Color: = clRed;

Pen.Color: = clGreen;

Pen.Style:= psDash;

Pen.Color: = clRed;

Explanation:

Exercise 4

Var i: integer;

Series1.Clear;

for i: = 0 to 22 do

Series1.AddXY (i * 0.29,10 *sin (i * 0.29), ”,clGreen) ;, where i * 0.29 (AXValue) this is an argument and 10* sin (i * 0.29) (AYValue)

  1. y = 3.2 * (14 * x)
  2. y = sin (x)
  3. y = cos (x)
  4. y = x 2 + cos (x)
  5. y = x 2 -4.5 * 4

Exercise 5

with ComboBox1 do begin

Items: = Screen.Fonts;

  1. Save and run the project.
  1. Assignment to work.
  2. Paste the code you wrote
  3. Conclusion on the work done. Topic : Using graphics capabilities.

    The purpose of the laboratory work- Get to know the graphics capabilities Delphi.

    Students must learn to:

    • Create any graphic pieces J
    • Use graphics capabilities
    • Apply graphics capabilities
    • Create charts

    Theoretical part

    Delphi allows you to develop applications that can display graphics: diagrams, drawings, illustrations. To display graphical information, the Delphi library provides components, the list of which is given in the following table:

    Pictogram Name Page Appointment
    Image Additional Used to display graphics: thumbnails, bitmaps and metafiles
    Shape Additional Used to build geometric primitives
    DrawGrid

    (table of figures)

    Additional Used to create a table in the application that can contain graphics
    Chart

    (diagrams and graphs)

    Additional Used to create charts and graphs
    Paintbox

    (drawing window)

    System Used to create some area on the form in which to draw

    In addition, you can display and enter graphic information on the surface of any window component that has a Canvas property. Drawings created during the execution of the application can be either motionless or animated.

    Shape : only conditionally can be attributed to the means of displaying graphic information, since it simply represents various geometric shapes, appropriately shaded. The main property of this component is Shape, which can take values, Brush(brush) - this property is an object of type TBrush that has a number of subproperties, in particular: the color (Brush.Color) and the style (Brush.Style) of the shape's fill. The third specific property of the Shape component is Pen, which determines the style of the lines.

    Image: main properties: Picture - is responsible for loading the image, Stretch - is responsible for the size of the image in the Image component, AutoSize - is responsible for the size of the component into which the image was loaded, taking into account the size of the image.

    Chart: To set the displayed values, you must use the methods of the Series. Let's take a look at three of them.

    Method Clear clears the series from previously entered data.

    Method Add: - Add (Const AValue: Double; Const ALabel: String; AColor: TColor)

    allows you to add a new point to the diagram. The AValue parameter corresponds to the added value of the function, and the value of the function argument is filled in automatically, so you do not need to set it, the ALabel parameter is the name that will be displayed on the diagram and in the legend, AColor is the color. The ALabel parameter is optional, you can set it empty: ”.

    Method AddXY- AddXY (Const AXValue, AYValue: Double; Const ALabel: String; AColor: TColor)

    allows you to add a new point to the graph of the function. The parameters AXValue and AYValue correspond to the argument and function. The ALabel and AColor parameters are the same as in the Add method.

    PaintBox: be on the System page. It is a simple canvas window where you can draw arbitrary images. Graphics tools are contained in the Font, Brush and Pen properties. The canvas (canvas) is contained in the Canvas property of the component. The painting itself is programmed in the onPaint event handler.

    Exercise 1

    1. Create a program that introduces you to the Image component. It is necessary to place the components: Label, Image, BitBtn, Button. Sign as in the image and upload any image. Adjust the components so that in Image1 the image fits into the frames, and in Image2 the image matches its size. Make tooltips, when you hover over each image, the Hint property is responsible for the hints, to display you need to enter the text and enable the hints in the ShowHint property.

    Assignment 2

    1. Increase the size of the shape, and add the following components: Shape, Label. Subscribe.
    2. Apply styles to each Shape component according to the image:

    Assignment 3

    1. For example, let's place the PaintBox component on a form. OnPaint handler:

    with PaintBox1, canvas do

    Brush.Color: = clRed;

    Pie (12,100,140,280,12,100,140,280);

    Pen.Color: = clGreen;

    Pen.Style:= psDash;

    Rectangle (120,60, Width, Height);

    Pen.Color: = clRed;

    Polyline ();

    TextOut (75,20, 'Your text can be here!');

    Explanation: The first line sets the fill color: Brush.Color: = clRed; The second draws part of the ellipse: Pie (12,100,140,280,12,100,140,280); The following lines set the parameters of the pen (how the shapes will have a border), width, color and line style: Pen.Width: = 4; Pen.Color: = clGreen; Pen.Style:= psDash; But in this case we will see one solid line, since if the thickness is more than one pixel, the line style will be psSolid (solid). The following line is responsible for drawing the square: Rectangle (120,60, Width, Height); The following command draws a red asterisk: Polyline (); The last line is responsible for the text output: TextOut (75,20, "Your text can be here!");

    Exercise 4

    1. Make a program that plots a given graph of the function y = 10 * sin (x)

    1. Enlarge the form and place the TChart component on it from the Additional tab, and place the Button, Label component. Stretch the new TChart to a convenient size for development.
    2. We go into the graph editor by double clicking on the component. Editing and customizing the appearance of Series. To do this, click Add and select the Line chart type and click OK. To change the title, press Title and enter the formula y = 10 * sin (x).
    3. Write the code for drawing the chart in the OnClick event of the Button component:

    Var i: integer;

    Series1.Clear;

    for i: = 0 to 22 do

    Series1.AddXY (i * 0.29,10 * sin (i * 0.29), ”, clGreen);

    Explanation: Method Series1.Clear; clears the series from the previously entered data, so that when updating there are no old values. To draw a graph, you need values, in our case 22 values, at which the graph is drawn by the function Series1.AddXY (i * 0.29,10 *sin (i * 0.29), ”,clGreen) ;, where i * 0.29 (AXValue) this is an argument and 10* sin (i * 0.29) (AYValue) function calculation value, ”(ALabel) the name that will be displayed on the diagram and in the legend can be left blank, and clGreen (AColor) is the line color.

    1. Complete the following task on your own: draw a graph of functions
    2. y = 3.2 * (14 * x)
    3. y = sin (x)
    4. y = cos (x)
    5. y = x 2 + cos (x)
    6. y = x 2 -4.5 * 4

    Exercise 5

    1. Create an application that allows you to view the characters in the system fonts.
    2. Enlarge the shape, place DrawGrid1, ComboBox1, Label. Set the following properties for the DrawGrid1 component: RowCount = 7, ColCount = 32, FixedCols = 0, FixedRows = 0, DafaultColWidth = 20, DefaultRowHeight = 20.
    3. To redraw the contents of each cell, create an OnDrawCell event handler for the DrawGrid1 component. To display the font characters, we will use the Canvas property of the DrawGrid1 component. We directly need the TextRect method of the Canvas property. This method is used to display text information in a specific cell. The event handler will look like this:

    DrawGrid1.Canvas.textrect (rect, Rect.Left, Rect.Top, char ((ARow + 1) * 32 + acol));

    1. Save the project. Make sure that the cells in the table display the characters in the default system font.
    2. To select a font, we will use the ComboBox1 component. In order for this component to contain all screen fonts, it is necessary to add them to the list when creating the form. The names of all screen fonts can be found using the Screen global variable of type TScreen. This variable is automatically added to all Delphi applications. The Screen variable contains information about the current state of the application screen: names of forms and data modules used by the application; data about the active form and the components used by this form; the size and resolution of the screen used; information about the cursors and fonts available to the application. Information about the fonts available to the application is contained in the Font property of the Screen variable.
    3. Create an onCreate event handler for the form and add statements to it:

    with ComboBox1 do begin

    Items: = Screen.Fonts;

    ItemIndex: = Items.IndexOf (Font.Name);

    1. Save and run the project. The DrawGrid1 component contains the characters of the font set in ComboBox1.
    2. In order to bind the value of the font name for DrawGrid1 and ComboBox1, let's create another event handler:

    DrawGrid1.Font.Name:=ComboBox1.Text;

    1. Save and run the project.
    1. Number, topic, purpose of the laboratory work.
    2. Assignment to work.
    3. Description of input, intermediate and result data with indication of their type.
    4. Program in the programming language.
    5. Program execution result (Entered data and received data)
    6. Paste the code you wrote
    7. Conclusion on the work done.

"Displaying Graphical Information in Delphi"
Theme plan:
1. Methods of displaying graphic
information in Delphi.
2. Displaying pictures.
3. Display of geometric
figures.

1. Methods for displaying graphic information.
There are several ways in Delphi
displaying graphic information:
Conclusion of pre-prepared
images (Image components,
Shape);
Building graphs and charts
(component Chart, etc.);
Imaging
programmatically (object
Canvas).

2. Displaying pictures.
Displaying pictures using
we examined the Image component in
one of the previous topics.
Here we look at an example
implementation of the simplest animation
by periodically changing
the displayed picture in
Image components.
Go for an example.


Displaying protozoa
geometric shapes on the form
provides a Shape component.

3. Display of geometric shapes.
The main properties of the Shape component:
Brush
Pen
Shape
Color (.Color) and style (.Style) for
filling the shape.
Color (.Color), style (.Style), width
(.Width) and output method (.Mode) of lines
figures.
Geometric shape view.

3. Display of geometric shapes.
From multiple Shape components
you can create simple drawings.
Programmatically changing the position
(.Left, .Top) size (.Width, .Height) and
the color (Brush.Color) of the Shape components
in the figure you can implement
elements of the simplest animation.
Consider an example.

4. Construction of graphs and diagrams.
Diagrams are intended for
better visualization
arrays of numerical data, their
visual display and analysis.
Example.
For charting in Delphi
there are several components,
one of them is the Chart component (section
TeeChart Std).

4. Construction of graphs and diagrams.
View of the Chart component after it
settings on the form:

4. Construction of graphs and diagrams.
In addition to the "Object Inspector", access to
properties of the Chart component, you can
get by opening a special window
dialog (right button on the component \
Edit Chart ...)
Add
data series
Change type
charts

4. Construction of graphs and diagrams.
Choosing a chart type:

4. Construction of graphs and diagrams.
Setting Properties for Coordinate Axes
(Axis):

4. Construction of graphs and diagrams.
The data to display is usually
transferred to the Chart programmatically,
example:
Series1.Clear; (clear batch)
for i: = 1 to N do
Series1.addxy (i, A [i], '', clGreen);
Value by
X-axis
Value by
Y-axis
Signature
X-axis
Data color
on the diagram
Consider a construction example
function graph y = Sin (x)

Further:
Laboratory work No. 13.1.
"Displaying pictures and geometric
figures, their animation ".
Exercise:
1) Develop an application to implement
the simplest animation by periodic
changing the displayed picture in
Image components. (The number of pictures is not
less than three, pick up pictures
on one's own).

Exercise:
2) Come up with and draw a picture from
Shape components. Programmatically
changing position, size or color
Shape components in the figure
to carry out elements of the simplest
animation.

Further:
Laboratory work No. 13.2.
"Construction of graphs and diagrams."
Exercise:
1) Modify app from
laboratory work No. 9 (Display
data in the table). Add opportunity
displaying some data from the table
on a bar or pie chart.
2) Build a graph of a given function.

List of components for displaying graphic information

To display graphic information in the Delphi library, the components are provided, the list of which is given in table 4.1.

Table 4.1 Components of displaying graphic information Pictogram

Component

Page

Description

Image

Used to display graphics: icons, bitmaps and metafiles.


PaintBox (window for drawing)

Used to create some area on a form in which to draw.


DrawGrid (table of figures)

Used to display non-text data in rows and columns.


Chart (charts and graphs)

The component belongs to the TChart family of components that are used to create charts and graphs.


In addition, you can display and enter graphic information on the surface of any Display of graphics on the Canvas.

Canvas Canvas is not a component, so strictly speaking it should not be covered in this book. But since many components, in particular, forms, have a canvas and the canvas provides the ability to display various graphic information, it is still advisable to give some initial information about the canvas.

A canvas is an area of ​​a component on which you can draw or display rendered images. It contains properties and methods that greatly simplify Delphi graphics. All complex interactions with the system are hidden for the user, so a person who is completely inexperienced in computer graphics can draw in Delphi.

Each point of the canvas has coordinates X and Y... The canvas coordinate system, as elsewhere in Delphi, has its origin in the upper left corner of the canvas. Coordinate X increases as you move from left to right, and the coordinate Y- when moving from top to bottom. Coordinates are measured in pixels. A pixel is the smallest element in the surface of a drawing that can be manipulated. The most important property of a pixel is its color.

The canvas has the property Pixels... This property is a two-dimensional array that controls the colors of the canvas. For instance, Canvas. Pixels matches the color of the pixel 10th from the left and 20th from the top. An array of pixels can be treated like any property: change the color by giving a pixel a new value, or determine its color from a value stored in it. For instance, Canvas. Pixels: = 0 or Canvas. Pixels: = clBlack is the assignment of the pixel to black.

Property Pixels can be used to paint on canvas. Let's try to draw a pixel-by-pixel graph of a sinusoid on the shape's canvas. To do this, in the event handler of the form OnPaint(drawing) you can insert the following code:

TForm1. FormPaint (Sender: TObject);

var, Y: real; // function coordinates, PY: longint; // pixel coordinates

begin: = clWhite;

for PX: = 0 to ClientWidth do

(X is the plot argument,

: = PX * 4 * Pi / ClientWidth ;: = Sin (X);

(PY - pixel coordinate,

: = trunc (ClientHeight - (Y + 1) * ClientHeight / 2);

(The color of the selected

pixel (About brightness))... Pixels: = 0;

end;

Run this test application and you should see the output shown in Figure 4.1a. The graph of the sinusoid turned out, although not very good, because is split into separate points - pixels.

Canvas - class object TCanvas has many methods that allow you to draw graphs, lines, shapes using the property Pen- feather. This property is an object, which in turn has a number of properties. One of them is a property you already know Color- the color with which the drawing is applied. The second property is Width(line width). The width is given in pixels. The default width is 1.

Property Style determines the appearance of the line. This property can take the following values:

The canvas has the property PenPos type TPoint(cm .). This property specifies the current pen position in canvas coordinates. Moving the pen without drawing a line, i.e. the change PenPos, produced by the canvas method MoveTo (X, Y). Here ( X, Y) - the coordinates of the point to which the pen is moved. This current point becomes the origin, from which the method LineTo (X, Y) you can draw a line to a point with coordinates ( X, Y). In this case, the current point is moved to the end point of the line and a new call LineTo will draw a point from this new current point.

Let's try to draw the sine graph from the previous example with the pen. In this case, the event handler of the form OnPaint may look like:

procedure TForm1. FormPaint (Sender: TObject);

var, Y: real; // function coordinates, PY: longint; // pixel coordinates

begin: = clWhite ;. MoveTo (0, ClientHeight div 2);

for PX: = 0 to ClientWidth do

(X is the plot argument,

corresponding to pixel with coordinate PX): = PX * 4 * Pi / ClientWidth ;: = Sin (X);

(PY - pixel coordinate,

corresponding to the Y coordinate): = trunc (ClientHeight - (Y + 1) * ClientHeight / 2);

(A line is drawn on the graph)... LineTo (PX, PY);

You can see the result of the application in this version in Figure 4.1 b. As you can see, the quality of the graphics has improved significantly.

The pen can draw not only straight lines, but also shapes. For a complete list of canvas methods that use a pen, see the Delphi online help. In the meantime, as an example, we will give only one of them - Ellipse that draws an ellipse or circle. It is billed as

procedure Ellipse (X1, Y1, X2, Y2: Integer);

where the parameters X1, X2, Y1, Y2 define the coordinates of the rectangle that encloses an ellipse or circle. For example, the operator

Ellipse (10, 40, 20, 50);

will draw a circle with a diameter of 10 and center coordinates (15, 45).

Shapes are generally drawn not empty, but filled with the canvas property Brush- brush. Property Brush is an object that in turn has a number of properties. Property Color defines the fill color. Property Style defines the fill pattern (hatching). The default is Style equals bsSolid, which means solid color Color.

At the pen Pen there is one more property that we have not considered yet. This property - Mode(mode). The default is Mode = pmCopy... This means that the lines are drawn with the color specified in the property Color... But other modes are possible, in which not only color is taken into account Color but also the color of the corresponding background pixels. The most interesting of these modes is pmNotXor- addition to the background by inverse exclusive OR. If this mode is set, then re-drawing the same shape at the same place on the canvas removes the previously drawn image and restores the pixel colors that were before the first image of the shape.

This feature of the mode pmNotXor can be used to create simple animations. It is enough to draw something, then erase what was drawn, redraw it slightly changed - and the drawing will seem to come to life.

Try to make yourself a simple animation - a moving circle. Start a new app and into the section implementation insert ad

X, Y: integer;

This will introduce global variables X and Y- the current coordinates of the image.

Into the form event OnPaint insert statements

Brush. Color: = clWhite ;: = clWhite ;. Pen. Mode: = pmNotXor;

The first of these operators sets the brush color to white. Brush... This means that your circle will be filled with white inside. The second operator sets the background color of the form surface to white.

The third operator sets the pen mode pmNotXor which will allow you to erase the old image before painting the new one.

Even the simplest animation needs synchronization. Otherwise, the speed of movement will be determined by the speed of the computer. Therefore, transfer the component to the form Timer- timer from the page System. This component is described in section 5.7 .

You can see its detailed description there. For now, set its property Interval equal, for example, 30 (this is the dwell time in milliseconds, but the real dwell time will be longer - see Section 5.7) and set the property Enabled equal false(this means that the timer will not start automatically when the application is launched).

To the event handler of this component OnTimer insert statements

// Erase the old image... Ellipse (X-5, Y, X + 5, Y-1Q); (X);

// Draw a new image... Ellipse (X-5, Y, X + 5, Y-10);

// Stop when reaching the end of the form

if(X> = ClientWidth-20) then... Enabled: = false;

The first of these operators draws a circle where it was drawn earlier, i.e. erases the previous image.

The last operator freezes the image at the edge of the form.

Now drag the button to the form Button and put the operators in the click handler on it

X: = 10 ;: = 100 ;. Ellipse (X-5, Y, X + 5, Y-10) ;. Enabled: = true;

The first two operators set the starting coordinates of the circle. The third operator draws the circle at its starting position, and the fourth starts the timer.

Translate the application, run it, click the button. You will see an image of a circle moving along the shape from left to right. And then just connect your imagination and transform this not too interesting application into something more fun.

On the canvas, you can display not only programmatically created images, but also images stored in graphic files. Only the canvas itself does not have a method to load an image from a file. Therefore, the file must be loaded into some other graphic object that can perceive the information of graphic files. And then rewrite the image from this object to the canvas using the canvas method Draw... Its description:

Draw (X, Y: Integer; Graphic: TGraphic);

Here the parameters X and Y define the coordinates of the upper left corner of the image placement on the canvas, a Graphic- an object that stores information. Such an object can be, for example, an object of type TBitMap, intended for storing bit matrices. Let's see how it all looks in practice.

Open a new application, drag the component to the form OpenPictureDialog from the Dialogs page (this is a component of the dialog for opening graphic files - see section 8.2 ) and the button Button... Place OpenPictureDialog anywhere on the form, since this component is not visual, and place the button at the bottom of the form. Add the code to the button click handler:

procedure TForm1. Button1Click (Sender: TObject);

var: TBitMap;

// Select a graphic file by the user

if OpenPictureDialog1. Execute then

// Create a BitMap object of type TBitMap: = TBitMap. Create;

// Bring the image to the form canvas... Draw (10, 10, BitMap);

// Destroy the BitMap object... Free;

end;

This code creates a temporary object of type TBitMap With name BitMap... Then the dialog for opening a graphic file is called OpenPictureDialog1 and if the user has selected a file, then it is uploaded to BitMap method LoadFromFile... Then by the method Draw The loaded image is copied to the canvas in the area with the coordinates of the upper left corner (10,10). After that the temporary object BitMap destroyed.

Run your application and click on its button. You will see that you can load any type of graphic file. bmp and it will be displayed on the canvas of the form (see Figure 4.2 a). You can find graphic files in the Images directory. In Delphi 5 and 4, it is usually located in a directory. \ program files \ Common Files \ Borland Shared. In Delphi 3, it is located in the directory. \ program files \ Borland \ Delphi 3, and in Delphi 1 - in the Delphi 16 directory. In the Images directory there is, in particular, the \ Images \ Splash \ 16Color \ subdirectory, which contains the file loaded in the example in Figure 4.2

You've created a pretty good application for viewing graphic files. But now let's try to see its major flaw. Without closing your application, go to some other program, for example, return to Delphi. Then, without doing anything there, go back to your running application. If the window of the program into which you left completely covered the window of your application, then returning to it you will see that the picture in the window has disappeared. If your application window was only partially overlapped, then returning to your application, you may see a result similar to that shown in Figure 4.2 b.

You can see that if the window of some other application temporarily overlaps the window of your application, then the image drawn on the form's canvas gets damaged. Let's see how you can eliminate this shortcoming.

If the window was overlapped and the image was corrupted, the operating system informs the application that something has changed in the environment and that the application should take appropriate action. As soon as a window update is required, an event is generated for it OnPaint... In the handler of this event (in our case, the event of the form), you need to redraw the image.

Redrawing can be done in different ways depending on the application. In our example, we could move out the declaration of a variable BitMap(operator var BitMap: TBitMap) outside of the above procedure, i.e. make this variable global by placing directly in the section implementation... Operator BitMap. Free could be moved to the form's event handler OnDestroy that occurs when the application is closed. Then, during the entire execution time of your application, you will have a copy of the picture in the component BitMap and you just need to enter into the event handler OnPaint forms just one operator:

Draw (10, 10, BitMap);

Do this, and you will see that the image on the form does not deteriorate for any overlapping windows.

In addition to the considered method Draw the canvas also has a copy method CopyRect:

CopyRect (Dest: TRect; Canvas: TCanvas; Source: TRect);

The method copies the one specified by the parameter Source image area in the canvas of the image source Canvas in the specified parameter Dest the area of ​​this canvas. A type TRect characterizing rectangular areas Source and Dest, already described in section 3.2 .

For example, the operator

CopyRect (MyRect2, Bitmap. Canvas, MyRect1);

copies to the canvas of the form in the area MyRect2 image from area MyRect1 component canvases Bitmap.

Copy method CopyRect produced in the mode set by the property CopyMode... By default, this property has the value cmSrcCopy, which means just replacing the image previously contained in the area Dest, onto the copied image. Other possible values CopyMode allow you to combine images, but their consideration is outside the scope of this book.

We will restrict ourselves to these basic information about the output of graphic information to the canvas. Section 3.2 information about the output to the canvas of the text was reported. In general, the canvas is a complex object with many more properties and methods. But this requires a detailed discussion that is beyond the scope of this book. The next book in the All About Delphi series will explore these issues in more detail.

A window component that has the property Canvas- canvas.

Image and PaintBox Components

Components Image and Paintbox represent some limited surface with a canvas on which images can be entered, as described in section 4.2 ... In this case, the component Paintbox, as a matter of fact, does not give anything new compared to drawing a form on the canvas. Drawing on Paintbox instead of form, it has no advantages, except, perhaps, some relief in the location of one or more patterns in the area of ​​the window.

But in addition to these capabilities, the component Image there are properties that allow you to work with different types of graphic files. Supports three types of files - bitmaps, icons and metafiles. All three types of files store images; the only difference is in the way they are stored within the files and in the means of accessing them. Bitmap (file with extension. bmp) displays the color of each pixel in the image. In this case, the information is stored in such a way that any computer can display an image with a resolution and number of colors corresponding to its configuration.

Pictograms (files with the extension. ico) are small bit matrices. They are ubiquitously used to represent application icons, in quick buttons, in menu items, in various lists. The way of storing images in thumbnails is similar to storing information in bitmaps, but there are some differences. In particular, the icon cannot be scaled, it retains the size in which it was created.

Metafiles do not store the sequence of bits that make up the image, but information about how the image was created. They store sequences of drawing commands that can be repeated when re-creating an image. This makes these files generally more compact than bitmap files.

Component Image allows you to display information contained in graphic files of all specified types. This is done by its property Picture- object of type TPicture.

Figure 4.3 Picture Editor window


To get acquainted with this property, open a new application and drag the component onto the form. Image... Stretch it or set its property Align equal alClient so that it occupies the entire client area of ​​the form. Click on the ellipsis button next to the property Picture in the Object Inspector window or just double click on Image... The Picture Editor window will open in front of you (Fig. 4.3), which allows you to load into the property Picture any graphic file (Load button), as well as save the open file under a new name or in a new directory. Click on Load to load the graphic file. You will see a window for opening a graphic file, shown in Fig.4.4 As you move the cursor in the list of graphic files, the right window displays the pictures they contain, and above them - the numbers characterizing the size of the picture. You can select any type of graphic file you need. Recall that the graphics files supplied with Delphi can be found in the Images directory. In Delphi 5 and 4, it is usually located in a directory. \ program files \ Common Files \ Borland Shared. In Delphi 3, it is located in the directory. \ program files \ Borland \ Delphi 3, and in Delphi 1 it is in the Delphi 16 directory. After downloading the file, click on OK in the Picture Editor window and in your component Image the picture you have selected will be displayed. You can launch your application and admire it. However, you can already see the picture without even running the application.

When you loaded an image from a file into a component during the design process Image, it not only displays it, but also stores it in the application. This gives you the ability to ship your application without a separate graphics file. However, as we will see later, in Image external graphic files can also be loaded while the application is running.

Let's go back to considering the properties of the component. Image.

If you set the property AutoSize v true, then the size of the component Image will automatically fit to the size of the picture placed in it. If the property AutoSize installed in false, then the image may not fit into the component, or, conversely, the area of ​​the component may turn out to be much larger than the area of ​​the image.

Another property is Stretch allows you to fit not the component to the size of the picture, but the picture to the size of the component. Install AutoSize v false, stretch or shrink component size Image and install Stretch v true... You will see that the drawing will take up the entire area of ​​the component, but since it is hardly realistic to set the dimensions Image proportional to the size of the picture, the picture will be distorted. Install Stretch v true may make sense only for some patterns, but not for pictures. Property Stretch does not work on images of pictograms, which cannot be resized.

Property - Center set in true, centers the image on the square Image if the size of the component is larger than the size of the picture.

Let's consider one more property - Transparent(transparency). If Transparent equals true, then the image in Image becomes transparent. This can be used to overlay images on top of each other. Place the second component on the form Image and load another picture into it. Just try to take some little filled, contour picture. You can, for example, take a picture from those usually placed on buttons, for example, an arrow (file. \ Program files \ common files \ borland shared \ images \ buttons \ arrow1l. Bmp). Move your Image so that they overlap each other and in the top component set Transparent equal true... You will see that the top picture is no longer obscuring the bottom one. One of the possible applications of this property is the imposition of inscriptions on the picture, made in the form of a bit matrix. These labels can be made using the Image Editor built into Delphi.

Note that the property Transparent acts only on bit matrices. In this case, the color of the lower left pixel of the bit matrix is ​​made transparent (i.e., replaced by the color of the image below it) by default.

We covered loading an image from a file during the design process. But the property Picture also allows you to easily organize the exchange with graphic files of any type during the execution of the application. To explain the technique of such an exchange, one must first consider in more detail the property Picture.

This property is an object, which in turn has sub-properties that point to the stored graphics object. If in Picture the bit matrix is ​​stored, pointed to by the property Picture. Bitmap... If an icon is stored, it is pointed to by the property Picture. Icon... The stored metafile is pointed to by the property Picture. Metafile... Finally, a graphical object of an arbitrary type is indicated by the property Picture. Graphic.

An object Picture and its properties Bitmap, Icon, Metafile and Graphic have file read and write methods LoadFromFile and SaveToFile:

procedure LoadFromFile ( const FileName: string);

procedure SaveToFile ( const FileName: string);

For properties Picture. Bitmap, Picture. Icon and Picture. Metafile the file format must correspond to the class of the object: bit matrix, icon, metafile. When reading a file into a property Picture. Graphiс the file must be in metafile format. And for the object itself Picture the read and write methods automatically adapt to the file type. Let us explain this with an example.

Let's build an application similar to the example of viewing graphic files discussed in section 4.2. For a change, you can organize control of it not by a button Button and the menu. Place a component on the form Image... Stretch it or set its property Align equal alClient so that it occupies the entire client area of ​​the form. Drag the graphic file open dialog component to the form OpenPictureDialog(see section 8.2 ). Place the main menu component on the form as well MainMenu(see section 6.1 ) and set one section in it - File. In the handler for this section, write the operator

(OpenPictureDialog1. Execute) then... Picture. LoadFromFile (. FileName);

This operator will call the dialog for opening a graphic file (see Fig. 4.4) and load into the component Image1 an image from a file selected by the user (see Figure 4.5). Moreover, the file can be of any type: bit matrix, icon or metafile.

Figure 4.5 Image in component Image bit matrix (a) and pictograms (6)



In this application, the method LoadFromFile applied to Image1. Picture... If only bit matrix files will be opened, then the file load operator can be replaced with

Picture. Bitmap. LoadFromFile (. FileName);

For pictograms, the operator could be used. Picture. Icon. LoadFromFile (. FileName);

and for metafiles, the operator. Picture. Metafile. LoadFromFile (. FileName);

or. Picture. Graphic. LoadFromFile (. FileName);

But in all these cases, if the file format does not match the intended one, an error will occur. The method works in a similar way. SaveToFile with the difference that applied to Picture or to Picture. Graphic it saves an image of any format to a file. For example, if you supplement your application with a dialog SavePictureDialog(see section 8.2 ), enter the Save as section in the menu and place the operator in its handler

SavePictureDialog1. Execute then... Picture. SaveToFile (SavePictureDialog1. FileName);

then the user will be able to save an image of any format in a file with a new name. Only in this case, in order to avoid further confusion, the extension of the saved file must still correspond to the format of the saved image.

The program will work absolutely identically for images of any format if you replace the save operator with

Picture. Graphic. SaveToFile (. FileName);

using property Picture. Graphic... And if you know the format stored in the component Image images, then you can apply the method SaveToFile to properties Picture. Bitmap, Picture. Icon and Picture. Metafile.

For all considered objects Picture, Picture. Bitmap, Picture. Icon and Picture. Metafile methods for assigning values ​​to objects are defined:

Assign (Source: TPersistent);

However, for BitMap, Icon and Metafile only the values ​​of homogeneous objects can be assigned: respectively, bit matrices, icons, metafiles. An exception is thrown when trying to assign values ​​to dissimilar objects EConvertError... An object Picture- universal, it can be assigned the values ​​of objects of any of the other three classes. And the value Picture can only be assigned to an object whose type is the same as the type of the object stored in it.

Method Assign can also be used to exchange images with the Clipboard. For example, the operator

Assign (Image1. Picture);

will add to the clipboard the image stored in Image1... Similarly, the operator

graphics delphi image app

Image1. Picture. Assign (Clipboard);

read in Image1 the image on the clipboard. Moreover, it can be any image or even text.

You just need to remember when working with the clipboard to insert into the operator uses your module link to the module Clipbrd... Delphi does not automatically insert this link.

Going back to the properties of the component Image, we can note one drawback inherent in our test application shown in Figure 4.5 When loading different images, the size of the application window may be either too small, and then you will see only part of the image, or too large, and then the image will be ugly placed in the upper left corner of the shape, leaving a lot of white space. This disadvantage can be eliminated by using the properties Height(height) and Width(width) component Image... With the property AutoSize established in true dimensions Image are automatically set equal to the size of the loaded image. And these dimensions can be used to resize the form accordingly. For example, the above code for loading an image from a file can be replaced with the following:

OpenPictureDialog1. Execute then

begin... Picture. LoadFromFile (. FileName) ;. ClientHeight: = Image1. Height + 10 ;. Top: = Form1. ClientRect. Top

+ (Form1. ClientHeight - Image1. Height) div 2 ;. ClientWidth: = Image1. Width + 10 ;. Left: = Form1. ClientRect. Left

+ (Form1. ClientWidth - Image1. Width) div 2;

end;

This code sets the client area of ​​the form to slightly larger than the component. Image1, which in turn adapt to the size of the picture due to the property AutoSize... Make these corrections to your application, run it and you will see that the form has begun to automatically adapt to the size of the uploaded image.

Shape component

Component Shape can only conditionally be attributed to means of displaying graphic information, since it simply represents various geometric shapes, appropriately shaded. The main property of this component is Shape(form), which can take on the following values:

Examples of these forms are shown in Figure 4.7.

Figure 4.7 Component examples Shape


Another essential property of a component is Brush(brush). This property is an object of type TBrush, which has a number of subproperties, in particular: color ( Brush. Color) and style ( Brush. Style) fill the shape. Fill at some values Style you can see in Figure 4.7 The third of the specific properties of the component Shape - Pen(pen) defining the line style. This property, like the property Brush, have already been considered in Section 4.2. ... You can find background information on these properties in Chapter 10 *.

Chart component

Now consider the component Chart... This component allows you to build various charts and graphs that look very impressive (Figure 4.8). Component Chart has many properties, methods, events, so if all of them are considered, then this would have to devote a whole chapter. Therefore, we will restrict ourselves to considering only the main characteristics Chart... For the rest, you can check out Delphi's built-in help, or just try them out by experimenting with diagrams.

Component Chart is a container of objects Series type TChartSeries- data series with different display styles. Each component can include several series. If you want to display a graph, then each series will correspond to one curve in the graph. If you want to display charts, then for some types of charts it is possible to overlap several different series, for others (for example, for pie charts) it will probably look ugly. However, even in this case, you can set for one component Chart several series of the same data with different chart types. Then, by making one of them active at each moment of time, you can provide the user with a choice of the type of chart that displays the data of interest.

Place one or two (if you want to reproduce Figure 4.8) components Chart on the form and look at the properties opened in the Object Inspector. Let us give an explanation of some of them.

Determines the ability of the user to scroll through the observed portion of the graph at runtime by pressing the right mouse button. Possible values: pmNone - scrolling is prohibited, pmHorizontal, pmVertical or pmBoth - scrolling is allowed, respectively, only in the horizontal direction, only in the vertical direction, or in both directions.

Allows the user to change the image scale during execution by cutting out fragments of a diagram or graph with the mouse cursor (in Figure 4.8 b below, the moment of viewing a fragment of the graph is shown in full, shown in Figure 4.8 a).

Specifies the title of the chart.

Defines the caption below the chart. None by default. The signature text is defined by the Text subproperty.

Defines a border around the chart.

Chart legend is a list of symbols.

MarginLeft, MarginRight, MarginTop, MarginBottom

Left, right, top, and bottom margin values.

BottomAxis, LeftAxis, RightAxis

These properties define the characteristics of the lower, left and right axes, respectively. Setting these properties makes sense for graphs and some types of charts.

LeftWall, BottomWall, BackWall

These properties determine the characteristics of the left, bottom and back edges of the three-dimensional display area of ​​the graph, respectively (see Fig. 4.8 a, bottom graph).

List of data series displayed in the component.

Enables or disables 3D display of the chart.

3D display characteristics.

The scale of three-dimensionality (for Fig. 4.8 it is the thickness of the chart and the width of the bands of the chart).


Next to many of the listed properties in the Object Inspector, there are ellipsis buttons that allow you to call one or another page of the Diagram Editor - a multi-page window that allows you to set all the properties of diagrams. Calling the Diagram Editor is also possible by double-clicking on the component Chart or by right-clicking on it and choosing Edit Chart from the pop-up menu.

If you would like to try to reproduce the application shown in Figure 4.8, double click on the top component Chart... You will be taken to the Chart Editor window (Fig. 4.9) to the Chart page, which has several tabs. First of all, you will be interested in the Series tab on it. Click on the Add button - add a series. You will be taken to a window (Figure 4.10), in which you can select the type of chart or graph. In this case, select Pie - a pie chart. Using the Titles tab, you can set the title of the diagram, the Legend tab allows you to set the parameters for displaying the diagram legend (list of symbols) or even hide it from the screen, the Panel tab determines the appearance of the panel on which the diagram is displayed, the 3D tab allows you to change the appearance of your diagram: tilt, shear, thickness, etc.

When you are working with the Chart Editor and have selected a chart type, in the components Chart your form displays its view with conditional data entered into it (see Fig. 4.11).

Figure 4.10 Choosing a chart type in the Chart Editor


Therefore, you can immediately observe the result of applying various options to your application, which is very convenient.

The Series page, which also has a series of tabs, allows you to select additional characteristics for the display of the series. In particular, for a pie chart on the Format tab, it is useful to enable the Circled Pie option, which will ensure that for any component size Chart display a chart in the form of a circle. On the Marks tab, the buttons of the Style group determine what will be written on the labels related to individual segments of the chart: Value - value, Percent - percent, Label - data names, etc. In the example in Figure 4.8, the Percent button is enabled, and the General tab is set to a percentage template to display only integer values.

You can, if you like, add to this component Chart another identical series by clicking the Clone button on the Series tab of the Chart page, and then for this new series, click the Change button and select a different chart type, for example, Bar. Of course, two different types of charts in the same picture will look bad. But you can turn off the indicator of this new series on the Series tab, and then provide the user with a choice of one or another type of chart display (below it will be shown how this is done).

Exit the Diagram Editor, select the lower component in your application Chart and re-set properties for it using the Diagram Editor. In this case, you will need to specify two series, if you want to display two curves on the chart, and select the Line chart type. Since we are talking about graphs, you can use the Axis and Walls tabs to define the coordinate characteristics of the axes and 3D edges of the graph.

This completes the design of the application's appearance. The only thing left to do is write the code that specifies the data you want to display. For our test application, let's just set some constant data in the pie chart, and the sine and cosine functions in the graphs.

To set the displayed values, use the series methods Series... Let's dwell on only three main methods.

Method Clear clears the series from previously entered data.

Method Add:

(Const AValue: Double; Const ALabel: String ;: TColor)

allows you to add a new point to the diagram. Parameter AValue matches the added value, parameter ALabel- the name that will be displayed on the diagram and in the legend, AColor- color. Parameter ALabel- optional, you can set it empty: "".

Method AddXY: (Const AXValue, AYValue: Double; ALabel: String; AColor: TColor)

allows you to add a new point to the graph of the function. Parameters AXValue and AYValue correspond to an argument and a function. Parameters ALabel and AColor the same as in the method Add.

Thus, the procedure for loading data in our example can be as follows:

155;=251;=203;=404;

var: word;

begin Series1 do

begin; (A1, "Shop 1", clYellow); (A2, "Shop 2", clBlue); (A3, "Shop 3", clRed); (A4, "Shop 4", clPurple);

end;. Clear ;. Clear;

for i: = 0 to 100 do

begin... AddXY (0.02 * Pi * i, sin (0.02 * Pi * i), "", clRed) ;. AddXY (0.02 * Pi * i, cos (0.02 * Pi * i), "", clBlue);

If you have provided, for example, for the data displayed in a chart, two series Series1 and Series4 different types - Pie and Bar, then you can introduce a procedure that changes the type of the chart at the user's request. This procedure can be injected into the event OnClick some button, into a menu command, or, for example, just to handle a click on a component Chart... In order to load data into Series4 and to make this diagram invisible at the first moment, you can insert at the end of the above procedure the statements

Assign (Series1) ;. Active: = false;

The first of these operators overwrites the data placed in Series1, in series Series4... And the second operator makes the series invisible Series4... Changing the type of diagram is carried out by the procedure

Active: = not Series1. Active ;. Active: = not Series4. Active;

In Figure 4.8 b, you can see the result of the user switching to a different view of the diagram.

Top related articles