Lesson 26

Introduction to Graphics

In this lesson, you will learn how to create graphics in Visual Basic 2015 using the Graphics and Pen objects.

26.1 Introduction

In earlier versions like VB6, drawing shapes was easy because built-in shape controls were available.

In VB.NET (including VB2015), you must write code to create graphics. Although this is slightly more complex, it gives you much more flexibility and control.

You can now create:

  • Lines
  • Shapes
  • Custom drawings
  • Advanced graphics

26.2 Creating the Graphics Object

Before drawing anything, you must create a Graphics object.

Dim myGraphics As Graphics = Me.CreateGraphics()

Other examples:

Dim myGraphics As Graphics = PictureBox1.CreateGraphics()
Dim myGraphics As Graphics = TextBox1.CreateGraphics()

This object allows you to draw on forms and controls.

26.3 Creating a Pen

A Pen is used to draw lines and shapes.

Dim myPen As New Pen(Color.Blue, 5)

Example:

Dim myPen As New Pen(Brushes.DarkMagenta, 10)
  • First argument → Color
  • Second argument → Line width

26.4 Drawing a Line

Private Sub BtnDraw_Click(...) Handles BtnDraw.Click

Dim g As Graphics = Me.CreateGraphics()
Dim pen As New Pen(Brushes.DarkMagenta, 10)

g.DrawLine(pen, 60, 180, 220, 50)

End Sub

Syntax:

DrawLine(Pen, x1, y1, x2, y2)

(x1, y1) = starting point (x2, y2) = ending point

Figure 26.1 – Drawing a Line

Build on This Foundation

Continue to VB2026

After learning the basics of checkbox controls in VB2015, move to the newest VB2026 tutorial for a more modern VB.NET learning path.

Explore VB2026 →

Visual Basic Programming

Visual Basic Programming

Use this Top Release book to reinforce your tutorial learning with a more structured guide.

Key Takeaways:
  • Graphics object is required to draw
  • Pen defines color and thickness
  • DrawLine creates lines
  • VB2015 graphics are code-based (more powerful)

Next: Drawing Rectangles

Go to Lesson 27 →