Quick Search for:  in language:    
GDI,article,explains,system,with,vbnet,replac
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
.Net Stats

 Code: 140,189. lines
 Jobs: 376. postings

 How to support the site

 
Sponsored by:

 
You are in:
 

Does your code think in ink?
Login





Latest Code Ticker for .Net.
Click here to see a screenshot of this code!Ray Picking for 3d Objects
By Jay1_z on 11/23

(Screen Shot)

Embed Images into Xml Files
By Chris Richards on 11/23


Encryption and Alternate Data Stream
By Philip Pierce on 11/23


Click here to see a screenshot of this code!AddressBook
By Ekong George Ekong on 11/23

(Screen Shot)

Click here to see a screenshot of this code!Command Line Redirection
By kaze on 11/23

(Screen Shot)

Fader
By Ahmad Hammad on 11/23


Click here to see a screenshot of this code!Get content of a web page (simple)
By Tin Trung Dang on 11/22

(Screen Shot)

Retrieve the long path name for a short path name.
By Özgür Aytekin on 11/22


Easy Randomizer
By Christian Müller on 11/22


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!

Affiliate Sites



 
 
   

Programming graphics in visual basic.net

Print
Email
 

Submitted on: 3/26/2002 5:02:07 PM
By: matt squire  
Level: Beginner
User Rating: By 15 Users
Compatibility:VB.NET

Users have accessed this article 20619 times.
 
(About the author)
 
     This article explains how to use the new GDI+ system with vb.net, this is the replacement for the old graphic drawing functions with loads more features.

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.

Drawing graphics in vb.net using GDI+, written by matt squire.

 

Introduction:

 

Visual studio .Net presents a new way of drawing graphics, which is based on drawing to a GDI surface rather than using the old line, circle and print methods. This technology will not be new to those of us who can write c++ but if you have only ever worked in VB then this is a completely new way of drawing, which is entirely different to the old ways, left over from BASIC.

 

How it works:

 

In simple terms each visible element on the screen (being a window) contains a GDI surface which can be drawn to. To draw to a control, an instance of the GDI class must be created and set to the controls window:

 

Dim MyGDISurface As Graphics = me.CreateGraphics

 

Here an instance of the gdi class, known as Graphics is created and then set to the forms window using its CreateGraphics method. All drawing will be done in MyGDISurface, this is where the real image is stored which is transferred to the form. This way of drawing graphics may seem long and sometimes pointless when you used to be able to just call a method or two to draw to a form but GDI has many more features, and can be drawn to anything.

 

Rectangles:

 

A rectangle is used to specify sizes and positions of shapes, it works like the standard x1,y1,x2 and y2 values, but uses height and width instead of x2 and y2. Rather than passing four parameters to a function, now you can just pass a rectangle object, individual x and y values can still be used instead of a rectangle as there are usually several versions of the same drawing function. A rectangle can be created using the code:

 

Dim MyRectangle as new Rectangle(1,1,100,218)

 

This means x1=1, y1=1, height=100, width=218

 

Pens, Brushes and fonts – drawing to your surface:

 

Now that you have created a working GDI surface, you can begin to draw graphics and that means – yes more class instances. Things are drawn differently in gdi, for instance to draw a line you specify its x,y,x2,y2 positions as normal (no rectangle in the line) and then use a pen object which sets the colour and line weight. The three most important objects used in the creation of graphics are pens, brushes and fonts:

 

  • Pen – defines line settings.
  • Brush – contains fill options.
  • Font – has font name, size and effects.

 

You create one of these in much the same way as any other class, for a pen you would type:

 

Dim MyRedPen as new pen(color.red)

 

An optional argument is line weight, which defaults to 1 if not specified:

 

Dim MyRedPen as new pen(color.red,3)

 

To draw a line with this pen you would use the code:

 

MyGDISurface.DrawLine(MyRedPen,1,1,100,253)

 

A brush contains settings for filling a shape, this could be in a square, circle or any multi-sided shape. A brush is created the same way as a pen and has the same one argument – colour:

 

Dim MyRedBrush as new SolidBrush(color.red)

 

This brush is very basic compared to what GDI+ is capable of. There are in all five GDI+ brush classes, these are SolidBrush, HatchBrush, TextureBrush, LinearGradientBrush and PathGradientBrush. A hatch brush is the same as solid except it uses a hatch style, Texture fills with a bitmap image, Linear gradient draws a simple gradient between two colours in various directions and a path gradient can be used to create more advanced gradients such as circular and square gradients. To use a hatch or either of the gradient brushes, your program must import System.Drawing.Drawing2D. The texture brush is included without importing this namespace. To import, insert the following code at the top of your program (above any classes).

 

Imports System.Drawing.Drawing2D

 

These examples show how to create the advanced brush classes. A hatch bush can be created in the same way a solid brush is created, only with more arguments - style, forecolour, backcolour.

 

Dim MyHatchBrush as new HatchBrush = new HatchBrush(HatchStyle.Plaid,color.red,color.blue)

 

The texture brush can fill objects using a bitmap; it must be passed the bitmap image as a bitmap object. The bitmap object can be created separately in a variable and then passed to the texture brush or it can be created in the texture brushes declaration, therefore eliminating the need for a new variable to be created:

 

Dim MyTextureBrush as new TextureBrush = TextureBrush(new bitmap(“c:\myimage.bmp”))

 

A gradient brush comes in two types; these are linear gradient – a simple fade between two colours and path gradient, which can create some very complex gradients. To create a linear gradient use:

 

Dim myBrush As New LinearGradientBrush(ClientRectangle, Color.Red,   Color.Yellow, LinearGradientMode.Vertical)

 

This code would create a vertical fade from red to yellow. This is fine for most drawing, but a path gradient can be used to create a far more complex gradient, which can create some interesting images. A path gradient uses a path object to define its behaviour, I won’t go into the path object in depth here but this example shows you how a simple path gradient is created:

 

' Create a path that consists of a single ellipse.

Dim path As New GraphicsPath()

path.AddEllipse(0, 0, 140, 70)

 

' Use the path to construct a brush.

Dim pthGrBrush As New PathGradientBrush(path)

 

' Set the color at the center of the path to blue.

pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255)

     

' Set the color along the entire boundary

' of the path to aqua.

Dim colors As Color() = {Color.FromArgb(255, 0, 255, 255)}

pthGrBrush.SurroundColors = colors

 

Fonts:

 

The font object is used to draw text; a font object contains the font name, size and information about effects such as bold, italic, underline. Here is a typical font class declaration:

 

Dim MyFont As New Font("Times new roman", 10, FontStyle.Bold)

 

This font could then be used in our GDI class to write “Hello world!” using MyFont and MyBrush at 1x, 1y:

 

MyGDISurface.DrawString(“Hello world!”,MyFont,MyBrush,1,1)

 

Some of the GDI+ functions:

 

Now that you understand how to use pens, brushes and fonts you can begin to explore the drawing functions, I will explain a few of these but to explain how every function works in detail would take forever and I am sure you can work out most for yourselves. The following code takes you through some simple functions.

 

        'create instance of graphics class, and set to forms client area

       Dim grap As Graphics = Me.CreateGraphics

        'create a read pen, with a thickness of 4

        Dim PenRed As New Pen(Color.Red, 4)

        'create a green brush

        Dim BrushGreen As New SolidBrush(Color.Green)

 

        'Draw an ellipse, using redpen

        'note that drawellipse does not draw a filled ellipse

        grap.DrawEllipse(PenRed, ClientRectangle)

        'draw a filled ellipse in the same place as

        'the previous ellipse, to create the

        'illusion of a filled ellipse with red, thick border

        grap.FillEllipse(BrushGreen, ClientRectangle)

        'draw a little rectangle in the bottom of the screen

        'instead of using the defualt version of this function

        'i used the second one so i could specify each

        'x and y position rather than a rectangle

        grap.FillRectangle(BrushGreen, 200, 200, 450, 450)

 

One more function I would like to mention is the arc, this function draws a section of a circle based on two angles. The curve is created using:

 

DrawArc(PenRed, centre x, centre y, arc width, arc height, start angle,  sweep angle)

 

The start angle is the angle from which the arc will begin, this is in angles and so has a maximum of 360 degrees, zero is at the bottom of the circle.

 

Conclusion:

 

I hope that from this article you learned the basics of visual basic’s new graphic drawing system. Anything you would like to say or add, just place a comment.

Visit http://www.3rdlife.net - my Half life / general game programming site

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
Your Vote!

What do you think of this article(in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments
3/27/2002 5:54:05 AM:roswellevent
Good Tutorial! Keep your Good Job ^_^
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/27/2002 4:38:13 PM:matt
thanks!, glad you like it and thanks for voting.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/28/2002 7:11:03 AM:D. de Haas
Looks great...! Thnx for sharing.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
4/18/2002 2:48:58 PM:Thraka
GoodJob but why not just learn directx?
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
4/18/2002 5:44:43 PM:matt
I wrote this for people who don't know GDI+, and I can program directX
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
4/19/2002 1:08:44 PM:WKocsis
Excellent article. How is VB6 Picturebox.Drawmode property handled in VB.Net?(Thanks)
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/3/2002 7:27:28 AM:matt squire
The drawmode property does not exist in .net, it's not nessecery since you have the pen object.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/9/2002 2:26:23 PM:Thraka
This is handy but a sample program would be better
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/13/2002 10:57:05 AM:Joseph Hicks
If the drawMode property (and etc) does not exest because of pen objects, how can I draw in XOR mode?
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/16/2002 8:55:17 AM:matt squire
Joseph hicks has a good point... the only way to get back the old drawmode functionality is to write it yourself. Check out MSDN lib 6 for explanations on how each one works and code some functions to do it. Each one works by manipulating the pen colour so it shouldent be too hard. Thanks to everyone who voted, including ian the big PSC boss guy. I'm going to upload another article about more advanced subjects soon and I will include something about draw mode.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/5/2002 10:17:01 PM:Pete
Why can't these programmers ever make programming langauges right... why do the graphics always have to be so SLOW. Guess it's back to learning DirectDraw for me again...
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/10/2002 4:34:07 AM:johnny
is there a way to move a graphic over a form without it flickering? or is directx the only way? coz everytime i repaint it it seems to flicker tremendously...
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/22/2002 9:00:35 PM:Steve
Great Article, Very Helpful. After the drawing a line how is it possible to move it to a new location through code. Untimately, I would like to be able to select the line with my mouse, and move it somewhere else. How is this done? Thanks again!
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/30/2002 7:56:39 PM:Praveen
There are functions to draw a line, arc etc.. but how do i draw a point on the form in VB.NET??? Lets I want to draw a fractal which requires me to use pset in VB6.. how do u do it in VB.NET?
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
9/29/2002 3:25:56 PM:
This is helpful but does anybody know how to take a System.Drawing.Graphic and SAVE it to the harddrisk? As a matter of fact, can you do ANYTHING with System.Drawing.Graphic? I've been trying to find a c# function of some sort for the System.Drawing.Graphic to copy it to anything that I can use to save it to the harddisk, such as Copy the graphic to a picturebox, then use picturebox.image.save to save it. Problem is, I can't find any way to do it. I can copy a picturebox.image into a graphic, but after I edit it (in the graphic form) I can't put it back into the picturebox. Any suggestions are appreciated.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/5/2002 5:43:01 AM:matt squire
Well it's a long ghot, but why not code your own?... For file save/load just dump 3 or 4 bytes (4 for transparency) into a file for every pixel on the image. A simmaler principle could be applied to transferring the image bettween controls. (NOTE: If i don't respond to any comments over the next month, sorry - having trouble with my connection.)
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/10/2002 11:16:29 PM:David Freiberger
Good code, i already figured most of this out myself, but i need help on how to do the rendering or saving the image because im trying to draw a graph on my comp and it disapears when the form repaints itselft.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/25/2002 1:33:13 PM:
To David: Put your routine in the form's Paint event.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/25/2002 1:35:25 PM:
Thanks Matt. Put some things in perspective. One question. How can the properties of a pen or brush be changed after construction or can they?
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/25/2002 7:25:47 PM:
Following up on David Freiberger's question, how do you do
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/25/2002 7:38:14 PM:
Following up on David Frieberger's question, how do you "Put your routine in the form's Paint event" ? (I know that the form's paint event can be found in the base class events. My question is conceptual.) Consider this example. I have some code ... 1 - Calculate some numbers 2 - Draw some lines based on the numbers using GDI+ Drawline 3 - Do some more stuff How do I move step 2 to the form's paint event?
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
12/20/2002 8:57:48 PM:
Hi, Is there any way to implement the VB 6's Scale() method in Vb. .NET?. I´m trying to achieve the zoom window in my application.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
1/8/2003 3:00:38 AM:
First,I want to say sorry,I speek English so hard,because I'm a Chinese,we always speek in Chinese.But I wish you can understand what I say. I found there is a error in your article :"this is in angles and so has a maximum of 360 degrees, zero is at the BOTTOM of the circle. "But the zero is maybe at the RIGHT of the circle.Isn't it? I have a same question as Joseph Hicks's.If the DRAWMODE is not exist in VB.NET,how can we draw XOR line (or use XOR PEN)simply in our program?Do we use API to do this only?
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
1/8/2003 4:24:26 PM:matt squire
You have a point, Thanks for correcting that. Zero is at the top right, and 360 at the top left side. As for drawmode - I said to someone else that they would have to write it themselves. Different drawmodes take the foreground and background colours and perform logical operations on them (such as and, or, not, etc...). I would like to investigate this myself since a lot of people want to know, I don't have time at the moment but i'll do so soon and let you know. You need to convert each byte of each colour into binary, then perform the xor operation. There isn't room to go into detail here, but i'll email you my results sometime.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
1/8/2003 10:51:06 PM:
Draw a Invert Rectangle by API: Public Declare Function Rectangle Lib "gdi32" Alias "Rectangle" (ByVal hdc As IntPtr, ByVal X1 As Integer, ByVal Y1 As Integer, ByVal X2 As Integer, ByVal Y2 As Integer) As Integer Public Declare Function SetROP2 Lib "gdi32" Alias "SetROP2" (ByVal hdc As IntPtr, ByVal nDrawMode As Integer) As Integer Private Sub DrawInvertRect() Dim hdcDraw As IntPtr hdcDraw = picDest.CreateGraphics.GetHdc SetROP2(h dcDraw, 6) Rectangle(hdcDraw, 10, 10, 200, 400) grpTest.ReleaseHdc(hdcDraw) End Sub
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/15/2003 5:32:41 AM:Mick Doherty
Zero is Right Middle and so is 360. There are 360 degrees in a circle and it ends where it starts. There is actually no 360 since after 359 we go back to zero.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | .Net Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.