Home » Visual Basic.NET

Drawing to a Component

17 June 2003 12,816 views No Comment

Visual Basic.NET comes with a new graphics API called GDI+ which allows the programmer to draw onto components. This tutorial bypasses the GDI+ API, and shows you how you can directly access the pixel array of the components image.

A GDI+ example

The following code draws a single red line to a PictureBox component using the GDI+ API.

	Dim canvas As Graphics = PictureBox1.CreateGraphics()
	Dim redPen As New Pen(Color.Red)
	canvas.DrawLine(redPen, 10, 10, 20, 30)

While the GDI+ does provide good support for most drawing operations, it’s always handy to be able to write your own drawing routines so that you can optimise them to work with your application in the best way possible.

Setting up the form class

To start, create a new project, go to the form designer and add a PictureBox component of any size called “pictBox”. Now add members to your form class, and add the "Imports" so that it looks like this:

Imports System.Runtime.InteropServices
Imports System.Drawing.Imaging

Public Class Form1
    Inherits System.Windows.Forms.Form

 Windows Form Designer generated code 

    Private bmp As Bitmap
    Private rect As Rectangle
    Private w As Integer
    Private h As Integer
End Class

Note: if you forget to add the "Imports" at the top of the class declaration, you’ll have problems finding function definitions later on in this tutorial.

Create a "Form1_Load&quot event handler for your form, and place the following code into it.

Private Sub Form1_Load(ByVal sender As System.Object, _
                       ByVal e As System.EventArgs) Handles MyBase.Load        
    w = pictBox.Width
    h = pictBox.Height
    bmp = New Bitmap(w, h, PixelFormat.Format24bppRgb)
    rect = New Rectangle(0, 0, w, h)
    pictBox.Image = bmp
End Sub

In this startup code, we had to create a bitmap for the PictureBox, since when it is created, its image property is set to nothing. If you are drawing to a different component, it is most likely that its image property will also be set to nothing in which case you will need to create the bitmap manually. Check the documentation on your component for details.

Now we have set up the form class, the next page will show you how to access the bitmap pixel array.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.