Posted by: Zeeshan Amjad | September 6, 2009

Using DrawingVisual class in VB.Net


This lightweight class is used to render the vector graphics, images, shapes, text etc on the screen. It is important that this class doesn’t provide any feature layout, input handling, focus and event handling to improve the performance.

Just like the ContainerVisual class, this class also needs container to host it. Container of this class has to be a object of FrameworkElement or its subclass. We can use Window as a container of this, because Window is also inherited indirectly from FrameworkElement class. We get a drawing context from RenderOpen function to draw something on the Visual. Here is an example to show this.

  1: Imports System.Windows
  2: Imports System.Windows.Media
  3: Imports System.Windows.Input
  4: Imports System.Globalization
  5: 
  6: Public Class MyWindow
  7:     Inherits Window
  8: 
  9:     Private dv As DrawingVisual
 10: 
 11:     Public Sub New()
 12:         Title = "DrawingVisual Class"
 13:         Width = 400
 14:         Height = 300
 15:         WindowStartupLocation = Windows.WindowStartupLocation.CenterScreen
 16: 
 17:         dv = New DrawingVisual()
 18: 
 19:         Dim dc As DrawingContext
 20:         dc = dv.RenderOpen()
 21: 
 22:         Dim rect As Rect
 23:         rect = New Rect(New Point(75, 75), New Point(25, 50))
 24:         dc.DrawRectangle(Brushes.Yellow, New Pen(Brushes.Navy, 2), rect)
 25: 
 26:         dc.Close()
 27: 
 28:         AddVisualChild(dv)
 29: 
 30:     End Sub
 31: 
 32:     Protected Shadows ReadOnly Property VisualChildrenCount() As Integer
 33:         Get
 34:             Return 1
 35:         End Get
 36:     End Property
 37: 
 38: 
 39:     Protected Overrides Function GetVisualChild(ByVal index As Integer) As Visual
 40:         If index > 0 Then
 41:             Throw New ArgumentOutOfRangeException("index")
 42:         End If
 43: 
 44:         GetVisualChild = dv
 45:     End Function
 46: End Class
 47: 
 48: Public Class wpf
 49:     Public Shared Sub Main()
 50: 
 51:         Dim win As MyWindow
 52:         win = New MyWindow()
 53: 
 54:         Dim app As Application
 55:         app = New Application()
 56:         app.Run(win)
 57:     End Sub
 58: End Class
 59: 

This program draws one ellipse, one rectangle and writes one string “Hello from DrawingVisual” on the screen. Here is the output of this program.

vcwpf_19

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: