1. Computing

How to create 2D Graphics using WPF for Visual Basic Programmers



When .NET replaced VB6, weeping and wailing rose up through the land, "Where did the Line component go?"

The Line component is back. In fact, Shapes include the Ellipse, Line, Path, Polygon, Polyline, and Rectangle.

As a very first example using Shape objects, here's a simple box with an X in it.

<Window x:Class="Window1"
   Title="WPF Graphics Example 1" Height="338" Width="322">
   <Canvas Height="300" Width="300">
         Margin="100 100"
         Stroke="Red" />
      <Line X1="100" Y1="100"
            X2="200" Y2="200"
            Stroke="Blue" />
      <Line X1="200" Y1="100"
            X2="100" Y2="200"
            Stroke="Green" />

The Canvas component is designed for these simple 2D graphics. For a comparison, try placing these shapes in the default container, Grid. You'll find that resizing the window gives you unsatisfactory results and the lines don't quite match up with the rectangle. Canvas supports absolute positioning of its child objects. To demonstrate how all this ties together with Visual Basic (and to demonstrate a different Shape component), here's a program that simply draws a random Polyline all over a Canvas component. I set up the program in XAML with this code first:

   <Canvas Height="250" Width="250">
      <Polyline Name="myPolyline"
         Stroke="Red" StrokeThickness="2" />
      Height="25" Width="75"
      VerticalAlignment="Bottom" />

When Button1 is clicked, the partial class that is paired with the XAML code is executed:

Private Sub Button1_Click( _
   ByVal sender As System.Object, _
   ByVal e As System.Windows.RoutedEventArgs)

   Dim myPointCollection As PointCollection = _
      New PointCollection()
   For i As Int16 = 1 To 99
      myPointCollection.Add( _
      New Point( _
      CInt(Int(251) * Rnd()), _
      CInt(Int(251) * Rnd())))
   myPolyline.Points = myPointCollection
End Sub

Click Here to display the illustration
Click the Back button on your browser to return

Geometry offers both more power and more complexity. The next page shows how Geometry works.

  1. About.com
  2. Computing
  3. Visual Basic
  4. Using VB.NET
  5. Learning WPF 2D Graphics with Visual Basic Programming

©2014 About.com. All rights reserved.