How to draw on a brand new bitmap using vb.net PDF Print E-mail
Written by Joris Bijvoets   
Tuesday, 15 December 2009 23:12

If you have to make a drawing of some kind (e.g. a custom graph or schematic overview) using GDI+ in Visual Basic.Net, you need a Graphics Object to draw upon.

How to draw on an existing image or bitmap?

Drawing on an existing picture is easy:

Dim MyImage As Image = System.Drawing.Image.FromFile(".\SomeFile.bmp")

Dim MyGraphics as Graphics = Graphics.FromImage(MyImage)

'Some VERY simple drawing, just for the example

Dim MyPen As New Pen(Color.Blue, 1)

Dim MyRectangle As New Drawing.Rectangle(10, 10, MyImage.Width - 10, MyImage.Height - 10)
MyGraphics.DrawRectangle(MyPen, MyRectangle)

'Just in case you like the modification very much

MyImage.Save (".\SomeNewFile.bmp", System.Drawing.Imaging.ImageFormat.Bmp)

 

How to make a bitmap from scratch to draw on?

The above is quite simple, like most things in life. Sometimes things are however a bit more complicated. If you need to build your bitmap yourself from scratch, without the help of a background image in a file, you have to do some magic. Well... magic is far too much honor for the code, it's rather a kind of understanding the different objects involved.

The problem lies in the image object (at least, that was my problem). You need the image object to obtain an Graphics object. You need the Graphics object, because this object does the real drawing. But you can't define a nice image object with some user-defined dimensions.

So, you use the following to get the desired image object:

Dim MyBitmap As New Bitmap(SomeWidth, SomeHeight)

Dim MyImage As Image = Image.FromHbitmap(MyBitmap.GetHbitmap)

Dim MyGraphics as Graphics = Graphics.FromImage(MyImage)

...

Now you have a Graphics Object to use for your artistic purposes.

 

Last Updated on Sunday, 17 January 2010 08:37