Home

GDI+ Drawing: Lines

 

A Line

A line is a junction of two points. This means that a line has a beginning and an end:

Line Definition

The beginning and the end are two distinct points. Based on this, a line is represented either with two Point values or by four numbers representing its values on the Cartesian axes. To draw a line, the Graphics class is equipped with the following overloaded DrawLine() method: 

Public Sub DrawLine(pen As Pen, pt1 As Point, pt2 As Point)
Public Sub DrawLine(pen As Pen, pt1 As PointF, pt2 As PointF)
Public Sub DrawLine(pen As Pen, x1 As Integer, _
		 y1 As Integer, x2 As Integer, y2 As Integer)
Public Sub DrawLine(pen As Pen, x1 As Single, _
		 y1 As Single, x2 As Single, y2 As Single)

If the line is represented with natural numbers, its origin can be specified as a Point pt1 and its end would be represented with a Point pt2. If the line is drawn using floating numbers, you can start it at one PointF pt1 and end it at another PointF pt2. Otherwise, you can specify the starting point with coordinates (x1, y1) and the end would be represented with coordinates (x2, y2). The same type of line can be drawn using decimal values from coordinates (x1, y1) to coordinates (x2, y2).

Here is an example that draws three lines:

Private Sub FormPaint(ByVal sender As Object, _
                              ByVal e As PaintEventArgs) _
                              Handles MyBase.Paint

            Dim penCurrent As Pen = New Pen(Color.Red)
            e.Graphics.DrawLine(penCurrent, 20, 20, 205, 20)

            penCurrent = New Pen(Color.Green, 3.5)
            e.Graphics.DrawLine(penCurrent, 40, 40, 225, 40)

            penCurrent = New Pen(Color.Blue, 7.25)
            e.Graphics.DrawLine(penCurrent, 30, 60, 215, 60)

End Sub

Line

A Series of Lines

The above DrawLine() method is used to draw one line. If you intend to draw a group of lines at once, you can use the Graphics.DrawLines() method. It is overloaded with two versions as follows:

Public Sub DrawLines(pen As Pen, points As Point())
Public Sub DrawLines(pen As Pen, points As PointF())

To use this method, you should first define an array of either Point for natural numbers that represent Cartesian coordinates or PointF for floating numbers. Here is an example:

Private Sub FormPaint(ByVal sender As Object, _
                              ByVal e As PaintEventArgs) _
                              Handles MyBase.Paint

            Dim Coordinates As Point() = {New Point(20, 10), New Point(205, 20), _
                                New Point(40, 40), New Point(225, 60), _
                                New Point(30, 80), New Point(215, 100)}

            Dim penCurrent As Pen = New Pen(Color.Red)
            e.Graphics.DrawLines(penCurrent, Coordinates)

End Sub

This would produce:

Drawing Lines
 

Home Copyright © 2008-2016, FunctionX, Inc. Home