Graphics and Fonts


The visual side of your applications can be very exciting, and the following bundle of drawing code snippets will help you really take advantage of some of the new graphic capabilities in your VB .NET. Use my ready-to-run code snippets to do everything from converting file image formats to writing your own screensavers, designing your own arty icons to adding gradient backdrops in code. Read on, Rembrandt!

Designing Your Own Arty Icons

You can create your own icons in VB .NET by selecting Project Add New Item from the menu, then choosing Icon File and clicking on Open. From here, use any of the dozen drawing tools to create your perfect ICO file. (See Figure 7-10.)

click to expand
Figure 7-10: Strangely, I didn t pass art .

To change a Windows form to use this icon, click on the ellipsis next to its Icon property in the Properties window. Then navigate to your project folder and select the ICO file you just created.

The Basics of Working with Fonts

You can list all the currently installed TrueType and OpenType fonts on your system by cycling through the font families in the System.Drawing.FontFamily.Families namespace.

For example:

 Dim MyFontFamily As FontFamily  For Each MyFontFamily In System.Drawing.FontFamily.Families      ComboBox1.Items.Add(MyFontFamily.Name)  Next 

You can set the font for a particular control in code by creating a new Font object, then setting it to the control Font property. For example:

 Dim MyFont As Font  MyFont = New Font("Verdana", 8)  TextBox1.Font = MyFont 

Crafty Conversion Between Graphic Formats

Download supporting files at www.apress.com .

The files for this tip are in the Ch7 ”Convert Image Format folder.

Need a function to convert between bitmap, GIF, EMF, JPEG, PNG, WMF, and ICO image formats, among others? Don t buy a third-party control: this conversion is exactly what my next crafty little snippet does. And all in a mere dozen lines of code.

Just call ConvertImage , passing in the filename of your current file, the desired format of your new file (using the enumeration), and your new filename. And that s it:

 Public Sub ConvertImage(ByVal Filename As String, _      ByVal DesiredFormat As System.Drawing.Imaging.ImageFormat, _      ByVal NewFilename As String)      ' Takes a filename and saves the file in a new format      Try          Dim imgFile As System.Drawing.Image = _              System.Drawing.Image.FromFile(Filename)          imgFile.Save(NewFilename, DesiredFormat)      Catch ex As Exception          Throw ex      End Try  End Sub 

Here s an example of using this to convert a GIF image into a Windows bitmap:

 ConvertImage("c:\img1.gif", _     System.Drawing.Imaging.ImageFormat.Bmp, "c:\img2 .bmp") 

Rotating and Flipping Is Easy!

Download supporting files at www.apress.com .

The files for this tip are in the Ch7 ”Rotate Image folder.

Back in the golden olden days of programming, rotating and flipping an image either meant performing complicated bit-by-bit image swaps or getting out your wallet to plunk down for a third-party control.

With the .NET Framework, the System.Drawing namespace makes it much easier. As we saw in the last tip, the Image class provides functionality that will bowl over graphic developers of old.

This book isn t about graphics, however, and so it isn t my intention to focus on them. But rotating and flipping images is a relatively common business requirement, especially with the number of letters scanned into modern applications and faxes received through the Internet, so this little tip is designed to demonstrate just how easy it can be.

Firstly, load your image into your application ”either directly into an Image object or into the PictureBox control, as so:

 PicBox.Image = System.Drawing.Image.FromFile("c:\sample.gif")  PicBox.SizeMode = PictureBoxSizeMode.StretchImage 

Then, behind your rotate buttons , add functions similar to the following:

 Dim objImage As Image = PicBox.Image  objImage.RotateFlip(RotateFlipType.Rotate90FlipNone)  PicBox.Image = objImage 

Here, we extract the graphic from behind our PictureBox control as an Image object. We then run the .RotateFlip method, passing in one of many possible enumeration arguments: here, we re using Rotate90FlipNone , meaning that it should rotate the image 90 degrees and not flip it. We could, however, have chosen RotateNoneFlipX for a horizontal flip. Or any of the other fourteen options.

Finally, we set the Image property of our PictureBox back to our Image object, and the control displays our newly rotated image. A complete doddle!

Drawing with Windows Forms

Download supporting files at www.apress.com .

The files for this tip are in the Ch7 ”Drawing folder.

This book deals primarily with the business world. We ve talked about databases, setting up Web services, and utilizing powerful encryption algorithms. But we haven t discussed drawing in your application. So, in the interest of developing your all-round super programmer mindset, let this tip serve as a quick overview.

First off, you may have noticed that there s no Shape control with .NET. If you want to draw, you need to revert to code. Thankfully, it s not all sticky API code anymore. Microsoft has repackaged all that old drawing functionality, added a little more, and christened it GDI+ (the old system was known as the GDI, standing for graphical device interface ).

How can you use it? Basic drawing is actually pretty simple. You need to know just three core pieces of information. First, when drawing, you need a digital sheet of paper to work with. This is an object based on the Graphics class, and, if you worked a lot with graphics in VB6, you re probably best imagining this as an encapsulated Windows device context.

When you have this area to work on, you need to know what tools to work with, and there are really only two possibilities here. There s our second item, the Pen class, which allows you to set up the style of line you want. And then there s our third item, the Brush class, which is designed for filling in areas and defining how that fill will look.

Once you have the items, you use methods of the Graphics object (our sheet of paper) to put the tools into work. All the Draw methods take your pen style and draw something, and all the Fill methods take your brush style and fill something. So, for example, I may call the FillRectangle function of my Graphics object, passing in a purple Brush object and various dimensions, and a purple rectangle would be drawn for me.

Let s look at a little sample code to help explain away this weird-sounding phenomenon . This commented snippet is intended to run behind a Windows form:

 ' Get Graphics object from our form, our "sheet of digital drawing paper"  Dim objGraphics As System.Drawing.Graphics = Me.CreateGraphics  ' Create new Pen, color blue, width 10  Dim objPen As New Pen(Color.Blue, 10)  ' Draw line using pen from  ' 45 across, 45 down to 95 across, 95 down  objGraphics.DrawLine(objPen, 45, 45, 95, 95)  ' Draw arc, this time using built-in green pen  ' 8 across, 10 down to 30 across, 30 down  ' with a 90 degree start angle and 180 degree sweep  objGraphics.DrawArc(Pens.Green, 8, 10, 30, 30, 90, 180)  ' Create new Brush-based object, color purple  Dim objBrush As New SolidBrush(Color.Purple)  ' Draw rectangle area using brush  ' start at 100 across, 100 down,  ' carry on for 50 across, 50 down  objGraphics.FillRectangle(objBrush, 100, 100, 50, 50)  ' Draw ellipse, this time using built-in orange brush  objGraphics.FillEllipse(Brushes.Orange, 10, 10, 30, 30) 

Understand what is happening here? We re just setting up our Pen - or Brush -inherited objects, then passing them along with parameters to methods of the Graphics object. (See Figure 7-11 for the result.)

click to expand
Figure 7-11: The colorful result of our lines of code

Speaking of the Graphics object, here s a reference list of the most popular drawing methods, alongside their core parameters (most of which have multiple overloaded implementations ):

  • DrawArc : Draws part of an ellipse. Parameters are Pen object, list of coordinates, and start/end angle values for the arc in degrees.

  • DrawBezier : Draws a Bezier curve. Parameters are Pen object and list of control points from which the curve is generated.

  • DrawLine : Draws a straight line. Parameters are Pen object and list of coordinates.

  • DrawString : Draws text to your area. Parameters are text to add, Font object, Brush -inherited object, and coordinates.

  • FillEllipse : Draws a filled ellipse (circle). Parameters are Brush -inherited object (such as the SolidBrush) and list of coordinates (or Rectangle object defining those points).

  • FillPie : Draws a pie section. Parameters are Brush -inherited object, list of coordinates (or Rectangle object), and start/end angle values for the pie segment in degrees.

  • FillPolygon : Draws a polygon (think a circle with eight sides). Parameters are Brush -inherited object, array of seven points, and fill mode. The seventh point automatically connects to the last to create the polygon.

  • FillRectangle : Draws a rectangle. Parameters are Brush -inherited object and list of coordinates.

Of course, that s not all. You can create transparent brush fills, for example. You can also use the GraphicsPath and Transform classes, which form the real plus part of GDI+. You can even incorporate DirectX to give your graphics real spunk.

Look up drawing (and related subitems) in the help index for more information. Alternatively, check out http://msdn.microsoft.com/vbasic/donkey.asp for Donkey .NET ”a rehash of a classic game, created in Visual Basic .NET and incorporating graphics to blow your socks off.

Add an Exciting Gradient Backdrop, in Code!

Download supporting files at www.apress.com .

The files for this tip are in the Ch7 ”Gradient folder.

Want to add a little more visual impact to your application? How about adding an appealing gradient backdrop to your forms and in just a few lines of code?

That s exactly what this next snippet of code does for you. It accepts top and bottom gradient colors as arguments, then defines the brush and area to paint and displays the effect. Here s the code you ll need:

 Private Sub DrawFormGradient(ByVal TopColor As Color, ByVal_          BottomColor As Color)      ' Draws a gradient using the specified colors      ' on the entire page      Dim objBrush As New Drawing2D.LinearGradientBrush _          (Me.DisplayRectangle, _          TopColor, _          BottomColor, _          Drawing2D.LinearGradientMode.Vertical)      Dim objGraphics As Graphics = Me.CreateGraphics()      objGraphics.FillRectangle(objBrush, Me.DisplayRectangle)      objBrush.Dispose()      objGraphics.Dispose()  End Sub 

Next, you need to call the code ”typically in response to the Paint event of your Form, like this:

 Private Sub Form1_Paint(ByVal sender As Object, _      ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint      DrawFormGradient(Color.Blue, Color.AliceBlue)  End Sub 

Here, we re running our function each time that our form is painted (that is, drawn on the computer screen). It then paints our gradient: a rich blue mixing into a lighter blue. (See Figure 7-12.) Of course, if that s too bold, you may opt for the more subtle White blending into PapayaWhip . Or the mysterious Black merging into DarkOrchid . Or the XP-styled White into CornflowerBlue . But the coloring is, of course, up to you.

click to expand
Figure 7-12: My blue to alice blue form. In black and white.

Two quick tips: with a little editing, you can change the brush from painting Vertical to Horizontal , ForwardDiagonal , or BackwardDiagonal ; and, in the interest of general usability, don t overuse gradients. It could be scary.

Starting Your Own Screensaver

Download supporting files at www.apress.com .

The files for this tip are in the Ch7 ”Screensaver folder.

Screensavers are often seen as a no-go area for VB .NET programmers. They re not even EXE files and surely fall more within the realm of graphic designers and game developers. Incorrect .

The simple fact is that a screensaver, with a .scr file extension, is nothing more than a renamed executable. It s a regular Windows application that has traditionally been developed to display images and look pretty, warding off the terrors of now nonexistent screen burnout.

If you view the Display options through the control panel, you ll see a list of existing screensavers. These are simply files with the .scr extension found in the Windows system directory (that is, c:\Windows\System32).

But how do these applications know to respond to do things such as display the settings box or launch the screensaver? By using parameters. (See The Power of Command-Line Parameters tip in Chapter 2 to find out how to read these.) Imagine you click on the Preview button ”Windows launches the related SCR file, along with the parameter /p . The application then needs to look at this value and preview display the screensaver.

Other standard parameters are available as well: /s informs the screensaver that it needs to display its settings box, and /a tells you to display a change password dialog box. Then there s the big one: the /s parameter indicates that you should run your full screensaver, perhaps displaying graphics in code and exiting when the user moves his or her mouse.

Seem simple enough? Matters like this are almost always best demonstrated through example ”and, thankfully, Microsoft has made that task a little easier for me. Surf over to http://msdn.microsoft.com/vbasic/downloads/samples/ and click the screensaver sample link, or access it directly at http://msdn.microsoft.com/library/en-us/dnvssamp/html/vbcs_CreateaScreensaverwithGDI.asp. (The files are also available at www.apress.com, alongside the source for this entire book.)

It doesn t demonstrate the more-advanced features, such as password support or utilizing preview mode, but it does provide a solid grounding on the basics. I ve personally written articles on some of the more-advanced features; you may want to check out Developer.com at www.developer.com to dig these up, or you can download existing .NET screensaver code by performing a quick search at www.googlegroups.com.

And that s it: a screensaver is just an EXE file renamed with an .scr extension and placed in the Windows system directory. It accepts parameters and responds accordingly .

Your task is to merge this knowledge together with a little nifty graphics code to create your own screensaver: perhaps a logo-based application that scrolls company news across the screen, or a saver that displays family photographs, selectable through the settings screen. Good luck!




The Ultimate VB .NET and ASP.NET Code Book
The Ultimate VB .NET and ASP.NET Code Book
ISBN: 1590591062
EAN: 2147483647
Year: 2003
Pages: 76
Authors: Karl Moore

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net