Blue Theme Orange Theme Green Theme Red Theme
 
Safari Books Online
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
ANTS Performance Profiler 6.0
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » VB.NET » GDI+ in VB.NET Tutorial for Beginners

GDI+ in VB.NET Tutorial for Beginners


GDI+ is next evolution of GDI. Using GDI objects in earlier versions of Visual Studio was a pain. This tutorial gives you a head start with GDI+ using VB.NET. In this tutorial, you will learn how to write graphics applications and understand the concept behind the System.Drawing namespace and its members.

Author Rank:
Total page views :  124408
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

GDI+ is next evolution of GDI. Using GDI objects in earlier versions of Visual Studio was a pain. In Visual Studio .NET, Microsoft has taken care of most of the GDI problems and have made it easy to use.

GDI+ resides in System.Drawing.dll assembly. All GDI+ classes are reside in the System.Drawing, System.Text, System.Printing, System.Internal , System.Imaging, System.Drawing2D and System.Design namespaces.

The first class we must discuss is the Graphics class. After the Graphics class, I will discuss other useful GDI+ classes and structures such as Pen, Brush, and Rectangle. The final part of this tutorial are some examples in C#.

The Graphics Class.

The Graphics class encapsulates GDI+ drawing surfaces. Before drawing any object ( for example circle, or rectangle ) we have to create a surface using Graphics class. Generally we use Paint event of a Form to get the reference of the graphics. Another way is to override OnPaint method.

Here is how you get a reference of the Graphics object:

Private Sub form1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs)
Dim g As
Graphics = e.Graphics
End Sub
'form1_Paint

OR
:

Protected Overrides Sub OnPaint(ByVal e As
PaintEventArgs)
Dim g As
Graphics = pe.Graphics
End Sub
'OnPaint

Once you have the Graphics reference, you can call any of this class's members to draw various objects. Here are some of Graphics class's methods:

DrawArc Draws an arc from the specified ellipse
DrawBezier Draws a cubic bezier curve
DrawBeziers Draws a series of cubic Bezier curves
DrawClosedCurve Draws a closed curve defined by an array of points
DrawCurve Draws a curve defined by an array of points
DrawEllipse

Draws an ellipse

DrawImage

Draws an image

DrawLine Draws a line
DrawPath Draws the line curves defined by a GraphicsPath
DrawPie Draws the outline of a pie section
DrawPolygon Draws the outline of a polygon
DrawRectangle Draws the outline of a rectangle
DrawString Draws a string
FillEllipse Fills the interior of an ellipse defined by a bounding rectangle
FillPath Fills the interior of a path
FillPie Fills the interior of a pie section
FillPolygon Fills the interior of a polygon defined by an array of points
FillRectangle Fills the interior of a rectangle with a Brush
FillRectangles Fills the interior of aseries of rectangles with a Brush
FillRegion Fills the interior of a Region

In .NET, GDI+ functionality resides in the System.Drawing.dll. Before you start using GDI+ classes, you must add reference to the System.Drawing.dll and import System.Drawing namespace. If you are using Visual Studio .NET for your development, you can add reference to the GDI+ library using following:

Creating this project is simple. Create a Windows application and add reference to the System.Drawing.dll using Project->Add Reference menu item. See Figure 1.

Figure 1. Adding reference to System.Drawing.dll

After that add these two lines.

Imports System.Drawing
Imports System.Drawing.Drawing2D

Note: If you create a Windows application using VS.NET, you only need write only one line.

Imports System.Drawing.Drawing2D

After that add a Form_Paint event handler using the Properties Window. See Figure 2.

 

Figure 2. Adding Form_Paint event handler.

Note: You can also add Form paint event handler manually described above. 

Graphics Objects

After creating a Graphics object, you can use it draw lines, fill shapes, draw text and so on. The major objects are:

Brush Used to fill enclosed surfaces with patterns,colors, or bitmaps
Pen Used to draw lines and polygons, including rectangles, arcs, and pies
Font Used to describe the font to be used to render text
Color Used to describe the color used to render a particular object. In GDI+ color can be alpha blended

The Pen Class

A pen draws a line of specified width and style. You always use Pen constructor to create a pen. The constructor initializes a new instance of the Pen class. You can initialize it with a color or brush.

Initializes a new instance of the Pen class with the specified color.

public Sub Pen(Color)

Initializes a new instance of the Pen class with the specified Brush.

public Sub Pen(Brush)

Initializes a new instance of the Pen class with the specified Brush and width.

public Sub Pen(Brush, float)

Initializes a new instance of the Pen class with the specified Color and Width.

public Sub Pen(Color, float)

Here is one example:

Dim pn As New Pen(Color.Blue) or Dim pn As New Pen( Color.Blue, 100 )

Some of its most commonly used properties are:

Alignment Gets or sets the alignment for objects drawn with this Pen
Brush Gets or sets the Brush that determines attributes of this Pen
Color Gets or sets the color of this Pen
Width Gets or sets the width of this Pen

The Color Structure

A Color structure represents an ARGB color. Here are ARGB properties of it:

A Gets the alpha component value for this Color
B Gets the blue component value for this Color
G Gets the green component value for this Color
R Gets the red component value for this Color

You can call the Color members. Each color name ( say Blue ) is a member of the Color structure. Here is how to use a Color structure:

Dim pn As New Pen( Color.Blue )

The Font Class

The Font class defines a particular format for text such as font type, size, and style attributes. You use font constructor to create a font.

Initializes a new instance of the Font class with the specified attributes.

public Sub Font(string, float)

Initializes a new instance of the Font class from the specified existing Font and FontStyle.

public Sub Font(Font, FontStyle)

Where FontStyle is an enumeration and here are its members:

Member Name Description
Bold Bold text
Italic Italic text
Regular Normal text
Strikeout Text with a line through the middle
Underline Underlined text

Here is one example:

Graphics g ;
Dim font As New Font("Times New Roman", 26) 

Some of its most commonly used properties are:

Bold Gets a value indicating whether this Font is bold
FontFamily Gets the FontFamily of this Font
Height Gets the height of this Font
Italic Gets a value indicating whether this Font is Italic
Name Gets the face name of this Font
Size

Gets the size of this Font

SizeInPoints

Gets the size, in points, of this Font

Strikeout Gets a value indicating whether this Font is strikeout (has a line through it)
Style Gets style information for this Font
Underline Gets a value indicating whether this Font is underlined
Unit Gets the unit of measure for this Font

The Brush Class

The Brush class  is an abstract base class and cannot be instantiated. We always use its derived classes to instantiate a brush object, such as SolidBrush, TextureBrush, RectangleGradientBrush, and LinearGradientBrush.

Here is one example:

Dim lBrush As New LinearGradientBrush(rect, Color.Red, Color.Yellow, LinearGradientMode.BackwardDiagonal)

OR

Dim brsh As New SolidBrush(Color.Red), 40, 40, 140, 140)

The SolidBrush class defines  a brush made up of a single color. Brushes are used to fill graphics shapes such as rectangles, ellipses, pies, polygons, and paths.

The TextureBrush encapsulates a Brush that uses an fills the interior of a shape with an image.

The LinearGradiantBrush encapsulates both two-color gradients and custom multi-color gradients.

The Rectangle Structure

public Sub Rectangle(Point, Size) or public Sub Rectangle(int, int, int, int)

The Rectangle structure is used to draw a rectangle on WinForms. Besides its constructor, the Rectangle structure has following members:

Bottom Gets the y-coordinate of the lower-right corner of the rectangular region defined by this Rectangle
Height Gets or sets the width of the rectangular region defined by this Rectangle
IsEmpty Tests whether this Rectangle has a Width or a Height of 0
Left Gets the x-coordinate of the upper-left corner of the rectangular region defined by this Rectangle
Location Gets or sets the coordinates of the upper-left corner of the rectangular region represented by this Rectangle
Right Gets the x-coordinate of the lower-right corner of the rectangular region defined by this Rectangle
Size Gets or sets the size of this Rectangle
Top Gets the y-coordinate of the upper-left corner of the rectangular region defined by this Rectangle
Width  Gets or sets the width of the rectangular region defined by this Rectangle
X Gets or sets the x-coordinate of the upper-left corner of the rectangular region defined by this Rectangle
Y Gets or sets the y-coordinate of the upper-left corner of the rectangular region defined by this Rectangle

Its constructor initializes a new instance of the Rectangle class. Here is the definition:

public Rectangle(Point, Size); or public Rectangle(int, int, int, int);

The Point Structure

This structure is similar to the POINT structure in C++. It represents an ordered pair of x and y coordinates that define a point in a two-dimensional plane. The member x represents the x coordinates and y represents the y coordinates of the plane.

Here is how to instantiate a point structure:

Dim pt1 As New Point(30, 30)
Dim pt2 As New Point(110, 100)

Some sample Examples:

Drawing a rectangle

You can override OnPaint event of your form to draw an rectangle. The LinearGradientBrush encapsulates a brush and linear gradient.

Protected Overrides Sub OnPaint(ByVal pe As PaintEventArgs)
Dim g As Graphics = pe.Graphics
Dim rect As New Rectangle(50, 30, 100, 100)
Dim lBrush As New LinearGradientBrush(rect, Color.Red, Color.Yellow, LinearGradientMode.BackwardDiagonal)
g.FillRectangle(lBrush, rect)
End Sub 'OnPaint

The output of the above code looks like Figure 3.

 

Figure 3. Drawing a rectangle.

Drawing an Arc

DrawArc function draws an arc.  This function takes four arguments.

First is the Pen. You create a pen by using the Pen class. The Pen constructor takes at least one argument, the color or the brush of the pen. Second argument width of the pen or brush is optional.

Dim pn As New Pen( Color.Blue ) or Dim pn As New Pen( Color.Blue, 100 )

The second argument is a rectangle. You can create a rectangle by using Rectangle structure. The Rectangle constructor takes four int type arguments and they are left and right corners of the rectangle.

Dim rect As New Rectangle(50, 50, 200, 100)
Protected Overrides Sub OnPaint(ByVal pe As PaintEventArgs)
Dim g As Graphics = pe.Graphics
Dim pn As New Pen(Color.Blue)
Dim rect As New Rectangle(50, 50, 200, 100)
g.DrawArc(pn, rect, 12, 84)
End Sub 'OnPaint

The output looks like this:

Drawing a Line

DrawLine function of the Graphics class draws a line. It takes three parameters, a pen, and two Point class parameters, starting and ending points. Point class  constructor takes x, y arguments.

Protected Overrides Sub OnPaint(ByVal pe As PaintEventArgs)
Dim g As Graphics = pe.Graphics
Dim pn As New Pen(Color.Blue)
' Rectangle rect = new Rectangle(50, 50, 200, 100);
Dim pt1 As New Point(30, 30)
Dim pt2 As New Point(110, 100)
g.DrawLine(pn, pt1, pt2)
End Sub 'OnPaint

The output looks like this:

 

Drawing an Ellipse

An ellipse( or a circle)  can be drawn by using DrawEllipse method. This method takes only two parameters, Pen and rectangle.


Protected Overrides Sub OnPaint(ByVal pe As PaintEventArgs)
Dim g As Graphics = pe.Graphics
Dim pn As New Pen(Color.Blue, 100)
Dim rect As New Rectangle(50, 50, 200, 100)
g.DrawEllipse(pn, rect)
End Sub 'OnPaint

The output looks like this:

 

The FillPath

Drawing bazier curves is little more complex than other objects.

Protected Overrides Sub OnPaint(ByVal pe As PaintEventArgs)
Dim g As Graphics = pe.Graphics
g.FillRectangle(
New SolidBrush(Color.White), ClientRectangle)
Dim path As New GraphicsPath(New Point() {New Point(40, 140), New Point(275, 200), New Point(105, 225), New Point(190, 300), New Point(50, 350), New Point(20, 180)}, New Byte() {CByte(PathPointType.Start), CByte(PathPointType.Bezier), CByte(PathPointType.Bezier), CByte(PathPointType.Bezier), CByte(PathPointType.Line), CByte(PathPointType.Line)})
Dim
pgb As New PathGradientBrush(path)
pgb.SurroundColors =
New Color() {Color.Green, Color.Yellow, Color.Red, Color.Blue, Color.Orange, Color.White}
g.FillPath(pgb, path)
End Sub 'OnPaint

The output looks like this:

 

Drawing Text and Strings

You can override OnPaint event of your form to draw an rectangle. The LinearGradientBrush encapsulates a brush and linear gradient.

Protected Overrides Sub OnPaint(ByVal pe As PaintEventArgs)
Dim fnt As New Font("Verdana", 16)
Dim g As Graphics = pe.Graphics
g.DrawString("GDI+ World", fnt,
New SolidBrush(Color.Red), 14, 10)
End Sub 'OnPaint

The output looks like this:

 


Login to add your contents and source code to this article
 About the author
 
Mahesh Chand
Mahesh is a software developer with over 13 years of experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle. If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments
Viagra by Antonio On January 13, 2006
Everybody loves your guestbook,so do i. discount viagra http://www.tory.up2.co.il/?discount-viagra [url=http://www.tory.up2.co.il/?discount-viagra]discount viagra[/url] buy tramadol http://freud.franklin.edu/ruehle01/_kbas/00000069.htm?buy-tramadol [url=http://freud.franklin.edu/ruehle01/_kbas/00000069.htm?buy-tramadol]buy tramadol[/url] generic cialis http://freud.franklin.edu/ruehle01/_kbas/00000055.htm?generic-cialis [url=http://freud.franklin.edu/ruehle01/_kbas/00000055.htm?generic-cialis]generic cialis[/url] buy viagra online http://balrog.sdsu.edu/~mlymanha/_reqdis/000004b5.htm?buy-viagra-online [url=http://balrog.sdsu.edu/~mlymanha/_reqdis/000004b5.htm?buy-viagra-online]buy viagra online[/url]
Reply | Email | Delete | Modify | 
high level question by gary On April 27, 2006

Hi Mahesh

I am a very novice programmer (and BRAND new to VB.net) and I cant figure something out about GDI+ (or maybe it is .NET programming in general...)...

What I am trying to do is this: open up a windows form, add a few numerical parameters into text boxes, then output (and save to a file) a graphic that is generated based upon those parameters. Sounds pretty simple. But, where I am having trouble is I cant figure out how I can get PaintEventArgs passed to me after i enter the data. I can either have my graphics drawn BEFORE I have chance to enter data into the for (by adding a MainForm_Paint event) or I can draw them on Button_Click, but then I cant access PaintEvent Args.

Everything I find online tells me what to do once I get PaintEvent Args, but nothing tells me HOW I can get it (except for on an _paint event, which isnt working). I am sure I am missing something simple, can you point me in the right direction?

thanks!

-gary

Reply | Email | Delete | Modify | 
Re: high level question by Arun On May 2, 2007
gary were u able to find a solution to your problem I m having the same problem...
Reply | Email | Delete | Modify | 
Problem in saving image by chirag On April 28, 2006

Sir,

I want to save image with drawings and drawn text

i save image using

image.save(path,bmpstyle)

Another problem that i face is

I open image in picture box
After changing Image, when i try to save image using save syntax it will give me error like file is in use

I am not using SaveDialog box because this file is store as a part of data

 

Thanx

Reply | Email | Delete | Modify | 
Visual Studio version question ? by Dale On March 23, 2007
Hello there I am wondering about the references for this drawing tool you are explaining here. Currently I am running a standard developers version (VB.NET) of visual studio 2003. I am not seeing the references you are mentioning such as the System.Text, System.Printing, System.Internal , System.Imaging, System.Drawing2D and System.Design in my reference library. Is this something that is only available in visual studio 2005? Thanks in advance for any advice you can provide. dsmith
Reply | Email | Delete | Modify | 
Visual Studio version question ? by Dale On March 23, 2007
Hello there I am wondering about the references for this drawing tool you are explaining here. Currently I am running a standard developers version (VB.NET) of visual studio 2003. I am not seeing the references you are mentioning such as the System.Text, System.Printing, System.Internal , System.Imaging, System.Drawing2D and System.Design in my reference library. Is this something that is only available in visual studio 2005? Thanks in advance for any advice you can provide. dsmith
Reply | Email | Delete | Modify | 
Re: Visual Studio version question ? by Mahesh On March 24, 2007
This code works in all versions of Visual Studio. You need to make sure to add reference to System.Drawing.dll and related Dlls. Right click on your project, select Add Reference and from the list select System.Drawing.dll and other related System.Drawing.XXX dlls.
Reply | Email | Delete | Modify | 
hai plase help me by madhu On May 22, 2007
iam not getting what u said but iam trying this problem since 1 week but no progress this is my requirement i need to draw some shapes on image in form i completed that task now my problem is how to create events to that particular shapes like when i click that fillellipse shape color must be changed and tooltop must say what i done in execution time can u plase guide me waht to do
Reply | Email | Delete | Modify | 
hai plase help me by madhu On May 22, 2007
iam not getting what u said but iam trying this problem since 1 week but no progress this is my requirement i need to draw some shapes on image in form i completed that task now my problem is how to create events to that particular shapes like when i click that fillellipse shape color must be changed and tooltop must say what i done in execution time can u plase guide me waht to do
Reply | Email | Delete | Modify | 
how to delete ................ by tony On September 19, 2007
hi mahesh, After drawing one line on picturebox I want to delete that line after some time means what i do?. can you give some codings for this?. tony
Reply | Email | Delete | Modify | 
Re: how to delete ................ by Mahesh On September 20, 2007
There is nothing called Delete. You will have to Redraw your PictureBox without drawing the line on it.
Reply | Email | Delete | Modify | 
Visio style objects by Brian On August 28, 2008
Is there a way to make these objects behave like visio object where you can click and drag?
Reply | Email | Delete | Modify | 
Re: Visio style objects by Mahesh On April 2, 2009
It will be a lot of work. I suggest to use any third party tool. There are already third part components you can use. Try Go.NEt or GoDiagram
Reply | Email | Delete | Modify | 
How can I move an object in GDI with VB.NET? by Joelle On March 17, 2009
I have a project about Chinese Chess wiht GDI. I have designed a frame to phay game but I haven't a way haow to play it?
Reply | Email | Delete | Modify | 
Re: How can I move an object in GDI with VB.NET? by Manish On April 8, 2009
HI
Use the move method of the object inside a timer for moving the object.

Private Sub Timer1_Timer()

    Text1.Move Text1.Left + 20

End Sub
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.