VB Lecture Notes - Graphics
Objective #1: Obtain and work with common graphics file types.
- Most types of graphics can be used in PictureBoxes. I recommend that you use gif and jpg graphics since they can easily be found on the Web (e.g. http://images.google.com ) and are sure to work with Visual Basic.
On a Windows PC, the file's graphic type can be determined by the file extension at the end of the file's name. If a file is named logo.gif then the file is a gif file. If it is named logo.jpg then the file is a jpg file.
- gif - Files of type gif are best for clip art, cartoon pictures and other illustrated graphics that have relatively few colors (e.g. a pacman graphic).
- jpg - Files of type jpg are better for digital camera photos or images with rich, varied color (e.g. the picture of a sunset).
- To save a graphic to your computer, you can right-click over the graphic and choose the Save Picture As menu command to place the graphic in your My Pictures folder.
- You can download graphics from the Internet though there are copyright
issues to be aware of. Some websites
allow you to use clip art for free. From other websites, the graphics are protected by copyright and you are not allowed to use a graphic in anything that you publicly distribute. However, if you
are using the graphic for a project in this VB course and the instructor is the only person that will see the graphic for grading purposes, then you may use the graphic in your VB project. The law provides an exception allowing you to use copyrighted material in certain educational reasons.
Objective #2: Use graphics with PictureBox objects.
- A PictureBox object can be used to display a graphic. The prefix pic is used for PictureBox objects.
- You can click the browse button that appears in the Image property of a PictureBox to make a graphic appear in the PictureBox. I recommend that you choose "Project resource file:" option that comes up in the Select Resource dialog box rather than the "Local resource:" option. The Project resource file option embeds a copy of the graphic into your project folder so you'll have access to it even if the original graphic is deleted or moved from its location (i.e. probably your My Pictures folder).
- The SizeMode property of a PictureBox can be changed to StretchImage to allow you to resize the graphic.
- If you selected added an image to a picture box using the "Project resource file" method as outlined above, you can change the graphic that is displayed in a picture box during run-time with the statement:
picPlayer.Image = ProjectName.My.Resources.Resources.pacmanright
The reference to pacmanright above would need to be replaced by the name of the graphic file that you added to your project without its file extension. If the name of the file is logo.jpg then you would replace pacmanright with logo. Also, you must type the name of your project in place of ProjectName in the example above. If your project's name includes blank spaces you must replace each blank space with an underscore character ( _ ). For example, if your project is named Hello World then ProjectName must be replaced by Hello_World.
- To clear an image from a picture box, use the statement
picGraphic.Image = Nothing
- Some graphics have annoying backgrounds that prevent the graphic from blending in nicely with your form's background color. If the graphic is a gif, see this tutorial to learn how
to make it transparent. You may also want to resize the graphic using a graphics program to reduce the filesize of the graphic.
- You will not be tested on the following technique but it may be useful in projects or assignments. Other than selecting an image by browsing your computer as explained above, another way to load an image into a picture box run-time is by using the statement
picPlayer.Image = Image.FromFile(Application.StartupPath + "\pacmanright.gif")
However, this requires that you place an actual copy of the graphic file (named pacmanright.gif in this example) in your project's bin/Debug folder. Note that this is the folder where the application's exe file is located.
System.AppDomain.CurrentDomain.BaseDirectory() can
be used instead of Application.StartupPath in
the example above.
- You will not be tested on the following technique but it may be useful in projects or assignments. A graphic can be rotated during runtime with the RotateFlip method. See the demo program in the Handout folder for more details.
Dim bmImage As New Bitmap(picPlayer.Image)
bmImage.RotateFlip(RotateFlipType.Rotate180FlipY)
picPlayer.Image = bmImage
Objective #3: Use color with objects.
- Using predefined color constants in the Color class you can assign colors various objects. This allows you to use a multitude of colors including Color.Red,
Color.Blue, and even Color.HotPink. For example, to set the background color of a PictureBox, you can use the statement
picPlayer.BackColor = Color.Blue
You can set the background color of the form itself using the statement
Me.BackColor = Color.Blue
The keyword Me must be used to refer to the form rather than the actual name of the form such as Form1.
- You can also use the FromArgb method to assign colors. For example, you can set the background
of a form to an interesting color with the statement
Me.BackColor = Color.FromArgb(45, 152, 99)
- The FromArgb method takes 3 parameters. All three parameters must be integers in the range 0 to 255. The first parameter refers to the amount of
red, the second refers to the amount of green and the third refers to the amount of blue. For example, to make the color blue, you would use the values 0, 0, 255 meaning that the resulting color has no red, no green and the maximum amount of blue. Using red, green and blue to create other colors is called the RGB additive color model which is used in many computer applications besides Visual Basic.
- To create the color black use 0, 0, 0. To create the color white, use the function 255, 255, 255.
- Here are websites that can help you with RGB values of interesting colors - http://www.cloford.com/resources/colours/500col.htm & RGB color calculator
Objective #4: Use the computer graphics coordinate system.
- Each object in your program has a location on the form based on a graphics coordinate system similar to how you graph points and lines on graph paper in math or geometry class. In Visual Basic's coordinate system, the x-axis values range from 0 to 300 as you follow across the screen from left to right. However, the y-axis (i.e. the vertical axis) is upside-down compared to the y-axis that you study in math and geometry classes. In VB, the y-axis values range from 0 to 300 as you go down the screen from the top.
- The width and height of the default size of a form are roughly 300 pixels.
- The properties Me.DisplayRectangle.Width and Me.DisplayRectangle.Height can be used to obtain the accurate dimensions of the form.
Objective #5: Use the DrawLine, DrawEllipse &
other methods.
- You can use the following drawing methods such as DrawLine in the Form1_Paint method as in
Private Sub Form1_Paint(...) ...
e.Graphics.DrawLine(Pens.Black, 10, 20, 10, 200)
End Sub
- You can print a word (i.e. string) on the form using the DrawString method as
in
e.Graphics.DrawString("Hello", New Font("Arial", 12), Brushes.Black, 30, 40)
where the text "Hello" will be printed in Arial font size 12 with the upper-left coordinate of 30, 40.
To make the text bold use
e.Graphics.DrawString("Hello", New Font("Arial", 12, FontStyle.Bold), Brushes.Black, 30, 40)
- You can draw a line segment with the DrawLine method.
e.Graphics.DrawLine(Pens.Black, 10, 20, 10, 200)
In this example, a black line will be drawn from the starting point (10, 20) to the end point (10, 200). That is, 10 is the x-coordinate of the one endpoint and 20 is
the y-coordinate of that endpoint. Ten would be the x-coordinate of the other endpoint and 200 would be that endpoint's y-coordinate.
To draw a line with more thickness, you can make this modification
e.Graphics.DrawLine(New Pen(Color.Black, 2), 10, 20, 10, 200)
where the 2 specifies a thicker pen.
- The DrawRectangle command allows you to efficiently draw a whole rectangle with one statement rather than using four separate DrawLine statements. For example
e.Graphics.DrawRectangle(Pens.Black, 50, 60, 100, 120)
would draw a rectangle that has a top, left position at (50, 60) where 50 is the coordinate on the x-axis and 60 is the coordinate on the y-axis.
The third number in the parentheses represents the width of the rectangle, 100 pixels in this case. The last number represents the height of the rectangle, 120 pixelsin this case.
Again, you can replace Pens.Black with something like New Pen(Color.Black, 2) in order to make a thicker outline around the rectangle.
- The FillRectangle command allows you to draw a rectangle that is filled in with color. For example
e.Graphics.FillRectangle(Brushes.Black, 50, 60, 100, 120)
would draw a solid, black rectangle. That position and size of the rectangle are determined with the numeric parameters in the same way as the DrawRectangle. Notice that you must use a brush rather than a pen with this method.
- An oval can be created using the DrawEllipse method. For example, the statement
e.Graphics.DrawEllipse(Pens.Black, 50, 50, 100, 200)
would draw a black oval that is bounded by a rectangle with a top-left corner at 50, 50 and a width of 100 pixels and a height of 200 pixels.
A perfect circle can be created using the DrawEllipse method as long as the last two parameters are equal. For example, the statement
e.Graphics.DrawEllipse(Pens.Black, 50, 50, 100, 100)
would draw a black circle that is bounded by a rectangle with a top-left corner at 50, 50 and a diameter of 100. For a circle, the last two parameters will be equal since the width and the height of a perfect circle are always equal. In other words, the diameter of the circle is the same no matter where or how you measure a circle.
- The FillEllipse command allows you to draw a filled oval or circle. For example
e.Graphics.FillEllipse(Brushes.Black, 50, 50, 100, 200)
would draw a solid, black oval. That position and size of the rectangle are determined with the numeric parameters in the same way as the DrawEllipse. Notice that you must use a brush rather than a pen with this method.
- You will not be tested on the following methods in this object but they may be useful in projects or assignments.
- The DrawPolygon method can be used to draw triangles, quadrilaterals, pentagons, etc.
Dim triangle() As Point = {New Point(50, 50), New Point(50, 200), New Point(100, 200)}
e.Graphics.DrawPolygon(Pens.Blue, triangle)
A triangle is drawn with the code segment above. You can add more points in order to increase the number of sides of the polygon.
- A filled polygon can be drawn with the FillPolygon method.
Dim triangle() As Point = {New Point(50, 50), New Point(50, 200), New Point(100, 200)}
e.Graphics.FillPolygon(Brushes.Blue, triangle)
A filled in triangle is drawn above. Notice that you must use a Brush instead of a Pen.
- The DrawLines method (which is different from the DrawLine method which does not end with an s) allows you to draw a bunch of line segments with one statement. You must first declare an array of points. Later in this course, we will study arrays and objects such as Points. But for now, all you need to realize is that you can specify as many points in the Dim statement as you'd like. The DrawLines method will "connect the dots".
Dim five() As Point = {New Point(100, 50), New Point(50, 50), New Point(50, 100), New Point(100, 100), New Point(100, 150), New Point(50, 150)}
e.Graphics.DrawLines(Pens.Red, five)
The number five is drawn by the code above.
- The DrawCurve method allows you to draw a smooth curve through a set of points. Similar to how the DrawLines method above will "connect the dots", the DrawCurve method connects the dots with a smoother line.
Dim five() As Point = {New Point(100, 50), New Point(50, 50), New Point(50, 100), New Point(100, 100), New Point(100, 150), New Point(50, 150)}
e.Graphics.DrawCurve(Pens.Red, five)
- The DrawClosedCurve method connects the dots like the DrawCurve above but it also connects the first dot with the last one.
Dim eight() As Point = {New Point(100, 50), New Point(50, 50), New Point(50, 100), New Point(100, 100), New Point(100, 150), New Point(50, 150)}
e.Graphics.DrawClosedCurve(Pens.Red, eight)
By changing the DrawClosedCurve to FillClosedCurve and using a Brush instead of a Pen, you can fill in the area outlined by the curve.
- The FillClosedCurve method works like the DrawClosedCurve method only it fills in the region with solid color.
Dim eight() As Point = {New Point(100, 50), New Point(50, 50), New Point(50, 100), New Point(100, 100), New Point(100, 150), New Point(50, 150)}
e.Graphics.FillClosedCurve(Brushes.Red, eight)
Notice that you must use a Brush instead of a Pen.
- With the DrawArc method you can draw an arc. By defining the coordinates of its bounding rectangle and setting the initial angle and the sweep angle (in degrees), you can trace out a smooth arc.
e.Graphics.DrawArc(Pens.Green, New Rectangle(0, 0, 100, 100), 0, 180)
creates a half circle inside the area outlined by the square with the upper-left corner of (0, 0) and width of 100. The 0 is the initial angle on the unit circle (3:15) and the amount of arc that is drawn is 180 degrees.
- The DrawBezier method can be used to draw curves similarly to how the Pen tool is used in graphics programs like PhotoShop.
e.Graphics.DrawBezier(Pens.Black, New Point(0, 150), New Point(50, 0), New Point(150, 100), New Point(200, 200))
- You can also draw an object to a buffer area using the form's CreateGraphics method. You are not responsible for knowing the CreateGraphics method
on tests or exams. Here's an example though:
Dim objGraphics As Graphics
objgraphics = Me.CreateGraphics
objgraphics.Clear(System.Drawing.SystemColors.Control)
objgraphics.DrawLine(System.Drawing.Pens.Chartreuse, 0, 0, 300, 300)
objgraphics.Dispose()
See this reference http://www.samspublishing.com/articles/article.asp?p=25723&seqNum=5&rl=1
- The statement
e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
can be used to make some of the methods above draw smoother lines.
- The command Me.Refresh() can be used to call the Paint method. Me.Update() may also work.
- Here is a demo program that illustrates some of the methods above: FromArgb, DrawLine, DrawRectangle, DrawEllipse, DrawString, FillRectangle,
FillEllipse, etc.
- Here is another demo program that illustrates how the methods can be placed into separate methods for increased reusability: Comic Strip Graphics Methods
- There are many other drawing methods that come from the Graphics class . You can learn how to use them by browsing the VB API. An API is
a list of classes and methods in a programming language. An API is meant to be used as a reference to professional programmers. Click the menu command View/Object Browser and then click the plus symbol
next to System.Drawing and the next System.Drawing entry. Highlight the Graphics class and browse through the window pane on the right to see other interesting drawing
methods that could be used in the example above.
Objective #6: Use Flash swf files in a VB project.
- You will not be tested on the following information in this objective but it may be useful in projects or assignments. However, the following information is provided since some students wish to add Flash movies to their VB programs.
- In order to use a Flash movie in a VB program, you must first create the Flash movie itself. Publish the movie
as a swf file and store that file in your VB project's bin/Debug folder folder.
- Add a reference to the COM SWF ActiveX control. Right-click on the tool box. Select “Choose Items…”. Select “COM Components”.
Select “Shockwave Flash Object”. Click OK.
- A new tool named Shockwave Flash Object now appears in your toolbox. Double-click the toolbox icon to place the Flash object on your form. The object will be named AxShockwaveFlash1
- Use the following code to play the Flash movie
AxShockwaveFlash1.Movie() = Application.StartupPath & "\vb flash demo.swf"
AxShockwaveFlash1.Play()
Later you can stop the Flash movie animation with the command
AxShockwaveFlash1.Stop()
When you are finished using the Flash movie in your project, you should clear it out of the memory with
AxShockwaveFlash1.Dispose()