Task 7: Graphics
The Graphics SCREEN
Points of Light
LINE Up Everyone
Going in CIRCLEs
PAINT by Numbers
Your Turn - USAFlag.BAS
BASIC originally came with a primitive set of graphics commands to create dots, lines, boxes, circles and to allow painting of screen areas. Even though the commands are very simple a creative programmer could do very interesting things with them. In this task we'll cover these primitive commands and in a later task step it up with new fancy graphics commands offered by QB64.
A quick note about new QB64 commands first
In this task commands are going to be introduced that were not native to the BASIC language but instead introduced by QB64. These new commands enhance the BASIC language to take advantage of today's more powerful computers and features that were not available many years ago. Most new commands introduced by QB64 start with an underscore ( _ ) character. This was done for compatibility reasons since QB64 was written to allow BASIC source code from the 80's, 90's, and 00's to compile and run.
One of the new commands you'll learn about is _NEWIMAGE(). Let's say someone wrote a program back in 1992 and created a variable in their code called NewImage%. If QB64 did not precede these new commands with an underscore that variable created way back then would be interpreted as a command in QB64. By adding the underscore to new commands old source code has a better than 99% probability of compiling and running just fine in modern versions of QB64.
A programmer can also create custom subroutines and functions and name them anything they like (more on subroutines and functions in a later task). If a programmer made a subroutine called NewImage() then again QB64 would interpret this as a command rather than a custom subroutine written many years ago.
There are literally hundreds of thousands, if not millions, of BASIC source code files scattered around the Internet. Because the developers of QB64 took compatibility into account you can be fairly certain that code from 1989 you found on the Internet will compile and run in QB64 today.
Before we get into graphics commands we need to learn about color use in QB64 first. Most graphics commands have a color option attached to them allowing for color customization. While there are options in QB64 to work with 256 color screens this course is only going to work with 32bit color (16 million) screens. This is just going to be a quick introduction to colors in QB64. We will delve into this topic in much greater detail in the advanced graphics task.
The _RGB32() statement is the most common way to set or create colors in QB64. There are a wide variety of color commands available in QB64 but this will be the one we use in this task. _RGB32() returns an unsigned long integer data type. Unsigned long integers have a range of 0 through 4,294,967,295 which is also the maximum value of a 32bit number (2^32 = 4,294,967,296). The _RGB32() statement creates colors by mixing red, green, and blue values together.
Color = _RGB32(red, green, blue)
There are 256 levels of each color available (0 through 255). By varying the levels for red, green, and blue you can make up to 16 million different color combinations (256 times 256 times 256 = 16,777,216). There is also a fourth optional parameter for changing the alpha layer, or transparency of a color, using the same 256 levels. This is why we need to use an unsigned long integer variable type to store color information (red(256) times green(256) times blue(256) times alpha(256) = 4,294,967,295). Unsigned long integers can be created with the use of ~& (the tilde character means "unsigned" and as we learned before the & character means long integer). Some examples are:
BrightRed~& = _RGB32(255, 0, 0) ' red set to full intensity
Red~& = _RGB32(127, 0, 0) ' red set to half intensity
BrightGreen~& = _RGB32(0, 255, 0) ' green set to full intensity
BrightBlue~& = _RGB32(0, 0, 255) ' blue set to full intensity
White~& = _RGB32(255, 255, 255) ' all three colors set to full intensity
Gray~& = _RGB32(127, 127, 127) ' all three colors set to half intensity
Many times you'll see programs that have constants set with common colors used throughout the source code:
CONST WHITE = _RGB32(255, 255, 255)
CONST GRAY = _RGB32(127, 127, 127)
CONST DARKGRAY = _RGB32(63, 63, 63)
CONST PURPLE = _RGB32(255, 0, 255) ' red and blue full intensity
CONST YELLOW = _RGB32(255, 255, 0) ' red and green full intensity
We'll get much deeper into the workings of color and the other color statements available in a later advanced graphics task.
The Graphics SCREEN
Up to this point we have been doing everything in a text only screen where graphics are not permitted. The first thing we need to do is get QB64 into a graphics screen mode. The SCREEN statement is used to do this. SCREEN 0 is the text mode we have been working with up to this point and is considered the default SCREEN. Since QB64 was developed to support GWBASIC and QuickBasic source code from the 80's and 90's, SCREEN 1 through SCREEN 13 modes are available. However, these legacy SCREEN modes are very limited in both size and colors available when working with today's graphics cards. If you are interested in learning about the legacy SCREEN modes you can click here to read about them on the QB64 Wiki.
In this course we are not going to bother with legacy SCREEN modes but instead use the new SCREEN options that QB64 has introduced for today's modern graphics cards.
Points of Light
Using the SCREEN statement along with QB64's _NEWIMAGE() statement you can create a graphics screen of any size with up to a 32bit color depth. Think of a graphics screen as a blank sheet of graph paper with each individual little square at your command. Each one of those little squares is known as a pixel which is the smallest point that can be referenced on a graphics screen. A pixel is literally a single point of colored light that you can control. Your computer's monitor screen is made of millions of pixels (2,073,600 for a 1920x1080 monitor). You can reference each and every one of those pixels using an X,Y coordinate system built into QB64. Type in the following program that illustrates how a graphics screen is laid out as shown in Figure 1.
Save the program as ScreenDemo.BAS when you have finished typing it in.
Figure 1 - A 640x480 Graphics Screen
A graphics screen of 640 pixels wide by 480 pixels high was created using this line of code:
SCREEN _NEWIMAGE(640, 480, 32) ' switch into a 640x480 graphics screen
The SCREEN statement is used to change the screen's mode. Back in the early days, when QuickBasic ruled, that could be a text only mode, SCREEN 0, or a few other options such as SCREEN 13 which set the screen to 320 pixels wide by 200 pixels high with a maximum of 256 colors. Screen modes also had fixed dimensions of 320x200, 640x200, 640x350, and 640x480. That's very small given today's very high resolution monitors. The early limitations had to do with limited video RAM on video cards and CRT monitors having fixed frequencies and dimensions. These limitations no longer exist today so those early legacy modes are of no use any longer.
QB64 introduced the _NEWIMAGE() statement to allow the programmer to create new images (a blank canvas if you will) in video RAM. By pairing the SCREEN statement with QB64's _NEWIMAGE() statement you can build a new screen image of any size you like. The _NEWIMAGE() statement requires three parameters:
_NEWIMAGE(width, height, colors)
Width is how many pixels wide, height is how many pixels high, and colors is the color depth desired, 256 for 256 colors and 32 for 32bit color (16 million colors). The _NEWIMAGE() statement is used for much more than just creating a screen but we'll cover that in another task on advanced graphics.
It's important to remember that to a computer zero is a number like any other and most operations start with zero instead of one. In the example program we created a 640 by 480 screen but Figure 1 points out that the coordinate system is actually referenced as 0-639 for width and 0-479 for height. That's because of the computer starting with zero. If you count zero as a number then 0 through 639 is actually 640 pixels and 0 through 479 is 480 pixels. That's also why in Figure 1 the center point is referenced as 319, 239 instead of 320, 240. Because the computer starts at zero everything seems "off" by one pixel. You'll need to remember this when creating graphics using QB64. Note that this is not something QB64 alone does, all programming languages use zero as a starting point for their graphics screen.
The PSET() statement is used to turn a single pixel on with a given color. PSET() requires the following parameters:
PSET(x, y), color
The x and y coordinate pair refer to the location on the screen where the pixel is to be manipulated. Color is provided by the _RGB32() statement which will be explained shortly. In the example program PSET() was used to turn the upper left (0, 0), middle (319, 239), and lower right pixel (639, 479) on with a color of white.
LINE Up Everyone
The LINE statement is used to draw lines, boxes, and filled boxes. The LINE statement takes the following parameters:
LINE(x1, y1) - (x2, y2), color, BF, style
The LINE statement needs a start coordinate (x1, y1), an end coordinate (x2, y2), a color, an optional B to create a box or an optional BF to create a filled box. An optional style can also be defined giving the line a pattern. Type the following program into your IDE to see all of the different ways LINE can be utilized. Save the program as LineDemo.BAS when you are finished.
As the above example code illustrates the B and BF parameters are optional. (x1, y1) is also optional. If you omit the start coordinates (x1, y1) from the LINE statement it uses the last known position as a starting point. Type in the next example to see how this works. Save the code as LineDemo2.BAS when finished.
You can even add a little style to the lines you draw. Type in the next example program and save it as LineDemo3.BAS when finished.
Figure 2 - A Line With Style
Setting up line styles is done by creating a value that contains a 16 bit pattern. For example, if you were to create a line using the number 43690 you would get a line with every other pixel turned on. Using the value of 65280 you would produce a dashed line. Type in the following code and execute it to see different style values being used and how they affect the line's output. Save the code as LineStyle.BAS when finished.
Decimal numbers ranging in value from 0 to 65535 translate to binary numbers containing 16 places. The decimal number 43690 can be converted to the binary number 1010101010101010 creating a pattern that can be used in the line's style. Where ever a 1 resides the line's pixel is turned on and a 0 means the pixel is turned off. This pattern is repeated over and over throughout the length of the line. Likewise, 65280 converts to 1111111100000000 in binary so you get a dashed line, 8 pixels on, 8 pixels off, 8 pixels on, 8 pixels off, and so on.
We're not going to get into decimal to binary conversion here. You can simply use a calculator that supports programmer functions, such as the Windows calculator, to type in the binary pattern you like and then have the calculator convert that pattern to decimal for you.
In the hands of a creative programmer the LINE statement can do some pretty wild things with very little code. Type the next program in and save as Illusion.BAS to see the LINE statement on digital drugs.
Figure 3 - Screenshot of Animated Illusion
And here is the code with straight lines. After typing in the code save this example as Illusion2.BAS.
Figure 4 - Makes the Eyes Go Doink!
Going in CIRCLEs
The CIRCLE statement is used to draw full or partial circles and ellipses onto a graphics screen. Let's start with a simple circle. The CIRCLE statement requires a minimum of three parameters:
CIRCLE (x, y), radius, color
The (x, y) pair are coordinates located on the graphics screen becoming the center of the circle. Radius is the distance from the center point to draw the circle. Remember that the radius of a circle is half the diameter. Color is optional but will probably always be supplied as the default white can get boring. Type the following code into your IDE and save as Circle.BAS when completed.
Figure 5 - A Yellow Circle
By default the CIRCLE statement draws a full 360 degree arc with an aspect ratio of one. You can override these values to draw only part of a circle, or an arc, by specifying the start and stop radian values of the arc. You can also supply an aspect ratio to change the circle into an ellipse.
CIRCLE (x, y), radius, color, start_radian, stop_radian, aspect
To better illustrate this type in the following program and execute it. Save the code as Radians.BAS when completed.
Figure 6 - Radian Demonstration
Radians fall in the range of 0 to 6.2831852 or 2 times Pi. Supplying the CIRCLE statement with positive radian values produces an arc from start_radian to stop_radian. Supplying negative radian values to CIRCLE produces the same arc but this time with lines drawn from the radian endpoints back to the center of the arc. This creates a pie looking structure as seen in Figure 6 above. Arcs are always draw in a counter-clockwise direction. If you were to designate Pi as the start radian value and half Pi as the end radian value the end result would not be an arc drawn between those two points in the upper left quadrant. The arc would include the entire circle except for this quadrant because of the arc being drawn counter-clockwise.
This Wikipedia article on radians does a very good job of explaining the relationship between a circle's radius and circumference.
The example program also illustrates how you can affect the CIRCLE statement's aspect ratio. The default aspect ration for the CIRCLE statement is 1 resulting in a perfectly round circle. Smaller aspect values squash the ellipse while larger values make the ellipse taller. If you simply want to change the aspect ratio of a circle without having to give radians you can simply skip over them like so:
CIRCLE (319, 239), 100, _RGB32(255, 255, 0), , , 2 ' create a tall yellow ellipse
By supplying no values for the start and end radian the CIRCLE statement uses the default values that create a closed arc, also known as a circle.
Here is a program that shows the power of the CIRCLE statement and how creative programming can use statements in ways that seem to defy their purpose. This example uses the CIRCLE statement to draw straight lines creating the hands of a clock and the tick marks going around the clock face. Save the program as CircleClock.BAS when finished.
Figure 7 - A Clock Made With Circles
PAINT by Numbers
While the LINE statement offers a way to create a filled box the CIRCLE statement does not offer a method of creating a filled circle. There also needs to be a mechanism for painting irregular shaped objects created with multiple LINE statements. This is where the PAINT statement comes in. Type in the following program to see the PAINT statement work its magic.
Figure 8 - A Painting
The PAINT statement is used to fill in an area with a color until another color is encountered. In the example program this line:
PAINT (319, 239), BRIGHTGREEN, GREEN
is instructing the computer to fill in a color at coordinate (319, 239) (the center of the circle) with the color bright green, _RGB32(0, 255, 0), until the color green, _RGB32(0, 127, 0) is encountered. The green color of the circle creates a border that the PAINT statement stays within. Since the portion of the red box inside the circle is not green the PAINT statement will paint right over top of it.
Because of the way the PAINT statement operates it's important to remember the order in which objects are drawn. Let's take the previous example and simply swap the LINE and CIRCLE statements so the circle is drawn first to see what happens.
Figure 9 - Well That Didn't Go As Planned?
Because the box was drawn over top of the circle the PAINT statement was able to spread out over the entire screen. Only where it saw green pixels did it stop leaving the partial circle as seen in Figure 9 above. The same result would happen if the box were not filled by the LINE statement:
Figure 10 - Holy Holes Batman!
Because the box is red instead of green it will create holes in the circle that the PAINT statement will exploit to allow paint to leak out and fill the screen as seen in Figure 10 above. Only by planning the order of graphics statements before-hand will you get the desired results with PAINT that you are looking for. Type in the following program and save it as CircleBounce.BAS when completed.
Figure 11 - Bouncing Painted Circles
We'll get the new commands seen in this program in later tasks. For now focus on the three constants contained in the code, CIRCLES, SCREENWIDTH, and SCREENHEIGHT. By changing the values of these constants you can change the entire look and feel of the program. The PAINT command takes quite a bit of horsepower from the CPU. You can see this by changing the constant CIRCLES to a large number. The larger the number the slower the code. By toggling the PAINT statement on and off you can see the difference in speed for yourself. Keep this in mind when designing graphics based programs using PAINT.
Recreate the following screen as shown in Figure 12 below using the graphics commands you learned from this task.
Figure 12 - Old Glory
- The width of the image is 640 pixels.
- Each red and white stripe is 36 pixels high.
- The blue banner is 310 pixels wide by 252 pixels high.
- The upper left hand circle is located at coordinate (30, 25).
- The first circle in the second row is located at coordinate (55, 50).
- All circles are spaced evenly horizontally and vertically 50 pixels apart.
- Look for patterns in the image above to reduce the size of your code using controlled loops.
- 22 lines of code (not counting REM statements) were created to produce the image in Figure 12.
- Try to create the flag in as few lines of code as possible (can you do it in less than 22?)
Save your code as USAFlag.BAS when finished.
Click here to see the solution.
Instead of circles create actual stars as seen in Figure 13 below.
Figure 13 - Bonus For Stars!
New commands introduced in this task:
New concepts introduced in this task:
Commands learned in Task 6:
DO...LOOP (and variations)
Concepts learned in Task 6:
Commands learned in Task 5:
SELECT CASE...END SELECT
colon ( : )
Concepts learned in Task 5:
order of operations
Commands learned in Task 4:
REM or '
Concepts learned in Task 4:
operators ( +, -, *, / )
Commands learned in Task 3:
Concepts learned in Task 3: