Programming for Computing 07 - 08

Chapter: Graphics

Module Admin   Contents, Index   Schedule  
1: Intro to VB    2: First Program and Projects    3: Variables, assignment, Strings    4: Type Conversion, InputBox, Constants    5:Built-in Functions    6: If - decisions    7: Loops - while, for    Example - find smallest    8: Scopes: local, global    9: Writing Procedures.Parameters, Functions   
10: Objects    11: Design    12: Testing    13: Graphics    14: Controls and events    15: Listboxes    16: Arrays    17: Files    18: The Command Line   

Appendices(links etc)   Additional Lectures    Tutorials (not in printed notes)     Selected solutions (not in printed notes)     Assignments    Additions and Errata   

new

The  schedule page has info on what we will do each week.

 


Section 13.0

Introduction

The term 'computer graphics' conjures up a variety of possibilities. We could be discussing a computer-generated Hollywood movie, a sophisticated video game, a virtual reality environment, a static photographic-style image on a monitor, or a more simple image built out of lines. Here we will restrict ourselves to the display of still images built from simple shapes. This simplicity is intentional, as we need to focus on the use of objects and methods, without being overwhelmed by graphics detail.

Here, we mainly look at the built-in procedures (also termed 'methods') for shape drawing. We need to pass parameters (or 'arguments'). These terms mean exactly the same thing.  


Section 13.1

Objects, procedures, (methods), properties, classes - an analogy

Although you don't really need to know about object-oriented programming at this stage, we provide a brief intro here. However, you can write graphics programs without a knowledge of the behind-the-scenes concepts of OOP.

Sometimes, you can approach object-oriented programming via an analogy. Here, we will look at the concept of a graphics drawing kit from a real-world point of view, and then from a computer object-oriented point of view. Please note that this is very much an introduction, and we will cover this material in more detail in following chapters.

In the real world, our drawing kit might consist of a pile of blank sheets of paper, some pens, and a set of shape-drawing tools ( for example a ruler, and a template with shapes cut out). The pens must match the paper: if the sheets are transparencies, then we might use oil-based pens.

Note that the paper by itself, or the template by itself, is not enough - it is the combination of them that provides us with the drawing kit.

In the computer's object-oriented world, we request that VB supplies us with a drawing area (rather like selecting 'new' in a word-processor). This drawing area comes with a set of procedures - also known as 'methods' (functions, operations) for shape-drawing. The idea of a sheet of paper that can do nothing goes against the object- oriented approach. To re-phrase: in VB's object style, we obtain a sheet of 'clever' paper, which comes with a set of facilities.

How many drawing kits can we create? There is no practical limit on a computer. For example, in a word-processor, you can create as many new document windows as you need, by clicking the 'new' button. In fact, in VB the word New is used to provide the programmer with newly-created objects to work with. When we use New, we must also specify what type of new object we require. In other words, we choose the class of the object. VB has a large collection of existing classes (such as buttons, labels, forms etc).

Let us move slightly closer to actual coding. The approximate code for drawing a rectangle is:

paper.DrawRectangle(details of color, rectangle position, etc.)
For now, we will ignore the details of the rectangle color and positioning. The main point is that paper is an object. We draw on it by using one of its methods. Here we chose DrawRectangle. Using a method is termed 'calling' or 'invoking' the method. To call a method of an object, we use the 'dot' notation, placing a '.' between the object and the method being called.

Objects can also have 'properties' as well as methods. We don't call properties - they don't do tasks for us. Rather, they let us access or change the current 'state' (settings) of an object. For example, the Text property of a button contains the message that the button shows. We can set this at design time, and in fact at run-time if we wish.

In the following code, we will be calling methods of the Graphics class provided by VB. It comes with a list of methods (such as DrawRectangle etc). Our drawing area - which we choose to name as paper - will in effect be a picture box control, available from the toolbox.

We will also be creating a new pen object and setting its color.

 


Section 13.2

A first drawing

Now we will create a program which displays two rectangles on a picture box when the button is clicked, as in figure 1. The instructions are all contained within one method. Here is the code listing:
Private Sub Button1_Click( _
                    ByVal sender As System.Object, _
                    ByVal e As System.EventArgs) _
                    Handles Button1.Click
    Dim paper As Graphics                             'always do this
    paper = PictureBox1.CreateGraphics()              '   and this
    Dim myPen As Pen = New Pen(Color.Black)           '   and this

    paper.DrawRectangle(myPen, 10, 10, 100, 50)
    paper.DrawRectangle(myPen, 10, 75, 100, 100)
End Sub
[graphics1.jpg]
fig 1 - first drawing

 


Section 13.3

Here is a summary of the control settings:
 
Control Property Setting
Button1 Text Draw
PictureBox1BackColor (Custom) White
PictureBox1 Size 150, 200
Form1 Text First Drawing

The final stage in creating the program is to double-click on the button and insert the drawing instructions. All of the instructions go within the Button1_Click1 method, as shown in the above code.

Run the program, then click on the 'Draw' button to see the two rectangles.

Now we will examine the detail of drawing shapes.  


Section 13.4

The graphics coordinate system

VB graphics are based on pixels. A pixel is a small dot on the screen which can be set to a particular color. Each pixel is identified by a pair of numbers (its coordinates), starting from zero:
  • the horizontal position, often referred to as x in mathematics, and also in the VB documentation. This value increases from left to right;
  • the vertical position, often referred to as y - this value increases downwards.
When we place a visual object on the screen, effectively we set its x/y position. Figure 2 shows a form of size 400 by 200, with a PictureBox placed at 200, 100. However, when drawing on the picture box, we regard its top left corner as being the zero point of horizontal and vertical coordinates. In other words, we draw relative to the top left corner of the picture box, not relative to the top left corner of the form. This means that re-positioning the picture box has no effect on any drawing it contains. We use this system when we request VB to draw simple shapes.

The size of the drawings depends on the quality of your screen, and on the graphics settings on your system. Higher-quality graphics has more (hence smaller) pixels, so your drawings will be smaller.

[graphics2.jpg]
fig 2 - coordinates

 


Section 13.5

Explanation of the program

We will not explain every detail of each line here - just the main points.

Our drawing code is contained within one method, named Button1_Click. There are two phases here: firstly we set up the drawing facilities, and then we actually draw. Here is the first part:

Dim paper As Graphics
paper = PictureBox1.CreateGraphics()
Dim myPen As Pen = New Pen(Color.Black)

The good news is that the above lines will be the same for most of our drawing programs. We will provide a brief explanation of these lines, but it is not essential that you understand every detail at this stage.
  • Line 1 is where we choose our name for the drawing area (we chose paper).The word Dim (short for 'dimension' ) allows us to choose a name for our object, and we must also choose its 'class' i.e. its type. It is a Graphics item (rather than a Button, for example, or an Integer)
  • In the second line, we link our drawing area to the picture box you placed on the form.
  • In Line 3, we choose a name for our pen. The word Pen is already in use by VB - it is the name of a class of item - so we went for myPen. At the same time, we set it to the color black.
This completes the preparation for drawing. You should use these three identical lines in all the programs in this chapter. We are now ready to put some shapes on our picture box.

To draw the shapes, we call (or invoke) VB's drawing methods/procedures. Here is the code:

paper.DrawRectangle(myPen, 10, 10, 100, 50)
paper.DrawRectangle(myPen, 10, 75, 100, 100)

The DrawRectangle method is one of the many methods provided by the VB system in a library. The statement shown is a call (also known as an invocation) of the method, asking it to carry out the task of displaying a rectangle. A method is so called because it is a method (or way) of doing something.

When we make use of the DrawRectangle method, we need to supply it with a pen, and with values to fix its position and size. We need to get these in the correct order, which is:

  • a Pen object;
  • the horizontal value of the top left corner of the rectangle;
  • the vertical value of the top left corner of the rectangle;
  • the width of the rectangle;
  • the height of the rectangle.
These items are known as arguments in VB. We can also also use the term 'parameter'. Here, the arguments are inputs to the DrawRectangle method. arguments must be enclosed in round brackets and separated by commas. This particular method requires five arguments, and they must be a Pen object, followed by four integers (whole numbers). If we attempt to use the wrong number of arguments, or the wrong type, we get an error message from the compiler. We need to ensure that:
  • we supply the correct number of arguments;
  • we supply the correct type of arguments;
  • we arrange them in the right order.
Some methods do not require any arguments. In this case, we must still use the brackets, as in:
PictureBox1.CreateGraphics()

Here, we have been calling pre-written methods, but with VB's help we have written our own method. VB has named it Button1_Click. We don't need to call it, because VB calls it for us when Button1 is clicked. Its task is to call the DrawRectangle method twice.



 


Section 13.6

Methods for drawing

As well as rectangles, VB provides us with facilities for drawing a range of shapes. Here, we have selected the simpler ones:
  • lines;
  • ellipses (i.e. ovals). This also includes circles.
  • filled rectangles and ellipses;
  • images from files.
Additionally, we can change the color of the pens we use for drawing, and use 'brushes' of a chosen color to fill shapes.

Here we list the arguments for each method, and provide an example program (Some Shapes) which uses them.

DrawRectangle

  • a pen object;
  • the horizontal value of the top left corner of the rectangle;
  • the vertical value of the top left corner of the rectangle;
  • the width of the rectangle;
  • the height of the rectangle.

DrawLine

Note that this method does not use the concept of an enclosing rectangle. The arguments are

  • a pen object;
  • the horizontal value of the start of the line;
  • the vertical value of the start of the line;
  • the horizontal value of the end of the line;
  • the vertical value of the end of the line.

DrawEllipse


Imagine the ellipse (an oval) squeezed inside a rectangle. We provide:
  • a pen object;
  • the horizontal value of the top left corner of the rectangle;
  • the vertical value of the top left corner of the rectangle;
  • the width of the rectangle;
  • the height of the rectangle.

To produce filled shapes we have:

FillRectangle

Its coordinate arguments are mostly identical to those of the Draw equivalent. The main difference is that the first argument must be a Brush object rather than a pen. Brushes can use a range of colors and textures. Here we only show the simplest untextured version:
Dim myBrush As SolidBrush = New SolidBrush(Color.Black)
paper.FillRectangle(myBrush, 10, 10, 90, 90)

FillEllipse

This is used in a similar manner to DrawEllipse, but with a brush rather than a pen.

DrawImage

This method is rather different, as it does not use preset shapes. Instead, it can be used to display images that have been stored in files. These images might have originated from a paint program, or from a scanner or camera. To use DrawImage, we firstly create a Bitmap object by providing the name of a file containing an image. The bitmap is created with Dim in the same way as we created a Pen object earlier. We then use DrawImage, specifying the bitmap, the position of the image, and the size of its containing rectangle. The image is clipped (trimmed to fit) if it is too big for the rectangle. The Some Shapes program below shows how to create the bitmap object, which we chose to name as pic. Our image was created in a paint package, and saved as imagedemo.jpeg. We can also work with gif and bmp file types.

The order of arguments for DrawImage is:

  • a bitmap object containing an image from a file.
  • the horizontal value of the top left corner of the rectangle;
  • the vertical value of the top left corner of the rectangle;
  • the width of the rectangle;
  • the height of the rectangle.

 


Section 13.7

Colors

It is possible to create as many pens and brushes as you wish, with their own colors. In VB, there are around 150 named colors. Below, we name the main colors, but also list some more obscure ones:
Black            Violet      Blue
Indigo           Green       Yellow
Orange           Red         Gray
Purple           White       Firebrick
LemonChiffon     Maroon      OliveDrab
  
We use the colors when creating pens and brushes.

Here is a program (called Some Shapes) which draws a variety of shapes. Figure 3 shows the resulting output.

Private Sub Button1_Click(...etc...


    Dim paper As Graphics
    paper = PictureBox1.CreateGraphics()
    Dim pic As New Bitmap("c:\mike\vbbook\imagedemo.jpeg")
    Dim myPen As Pen = New Pen(Color.Black)
    Dim fillBrush As SolidBrush = New SolidBrush(Color.Gray)
    paper.DrawRectangle(myPen, 10, 10, 100, 50)
    paper.DrawLine(myPen, 10, 10, 110, 60)
    paper.DrawRectangle(myPen, 10, 80, 100, 50)
    paper.DrawEllipse(myPen, 10, 80, 100, 50)
    paper.FillEllipse(fillBrush, 10, 150, 100, 50)
    paper.DrawRectangle(myPen, 130, 10, 150, 150)
    paper.DrawImage(pic, 130, 10, 150, 150)
End Sub
[graphics3.jpg]
fig 3 - some shapes

Create the program in the same manner as the First Shapes one, but make the picture box larger: to 300, 300.

 


Section 13.8


Problems
1. Write some VB instructions which produce a filled black circle of 50 pixels radius, 10 pixels in from the top left corner of a picture box.

2. Write and run a program which draws a large 'T' shape on the screen, with blue lines.

 


Section 13.9

Summary

  • Statements are obeyed in sequence, top to bottom (unless we request otherwise).
  • VB has a set of 'draw' methods which you can call up to display graphics.
  • Graphics positioning is based on pixel coordinates.
  • Argument values can be passed into methods.
 


Section 13.10

Problems

In the following, we recommend that you do rough sketches and calculations prior to writing the program. You can use the same project for each question, using a picture box for drawing, and a button event to initiate the drawing.

1 Write a program which draws a right-angled triangle. Choose an appropriate size.

2 Write a program which draws an empty tic-tac-toe (noughts and crosses) board, made out of lines.

3 Design a simple house, then write a program which draws it.

4 Here are some annual rainfall figures for the country of Xanadu, which we wish to display graphically:

    1998    150 cm
    1999    175 cm
    2000    120 cm
    2001    130 cm
(a) display the data as a series of horizontal lines.

(b) Instead of lines, use filled rectangles.

5 Write a program which displays an archery-style target with concentric circles of different colors. The purchase of a rubber sucker gun to fire at the screen is optional.

6 Write a program which displays a simple face. The outline of the face, the eyes, ears, nose, and the mouth can be formed by ellipses. 7 Create an image in a paint package, and save it as a bmp, gif, or jpeg file. Write a program which displays this image, and use DrawRectangle to provide a suitable frame round the image.

 


Section 13.11

new

Animation

At its simplest level, animation is drawing a shape, moving it, and drawing it again. Between each drawing, we may choose to clear the screen, so the movement does not leave a trail.

Another approach is to place a picture into a small picture box, then move the picture box itself. This is not shown here.

To draw at regular intervals, we put a Timer on the form. We can set its interval (i.e how many milliseconds between each tick) and switch it on and off (setting its 'enabled' property to true/false).

The following program has:

  • 2 buttons - one provides a moving filled circle, with no clearing of the picture box between draws.

    The other button provides a similar shape, but the circle bounces off each side of the picture box.

  • There is a picture box, whose backColor property is set to e.g. white
  • To run it, you need to create the 2 buttons and the picture box, and also put 2 timers onto the form.
  • The timers are not visible on the form, but they still work.
  • As soon as you put a timer on the form, double-click each timer to generate the sub..._Tick code, as seen at the bottom of the following code. Any code we place in the Tick sub gets done at regular intervals, automatically.
  • 
    ' animation examples
    Public Class Form1
    
        'globals
        Dim paper As Graphics
        Dim fillBrush As SolidBrush = New SolidBrush(Color.Blue)
        Dim x As Integer
        Dim xStep As Integer = 10    'change x by this, for every tick of Timer2
        '---------------------------------------------------
    
        Private Sub simpleButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles simpleButton.Click
            paper = PictureBox1.CreateGraphics
            Timer1.Enabled = True   'for simple
        End Sub
        '--------------------------------------------------------
    
        Private Sub bouncingButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bouncingButton.Click
            paper = PictureBox1.CreateGraphics
            Timer2.Enabled = True    'for bouncing
        End Sub
        '------------------------------------------------------
    
        'simple
        Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
            paper.FillEllipse(fillBrush, x, 20, 50, 50)
            x = x + 10   ' for next tick, this increased x will be used
        End Sub
        '--------------------------------------------------------
    
        'bouncing
        Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
            PictureBox1.Refresh()     'clear the picture box
            paper.FillEllipse(fillBrush, x, 20, 50, 50)
            x = x + xStep
            
            'test if we are at either edge of pic box
            If x > PictureBox1.Width Then    ' at right edge, so reverse
                xStep = -xStep     ' the step is now -ve, thus reducing x
            End If
    
            If x < 0 Then    ' at left edge, so reverse
                xStep = -xStep     ' the step is now +ve
            End If
        End Sub
    End Class
    

Module Admin   Contents, Index