New User?   Join Now     Login            Forgot Password?    
Drawing in Silverlight  (24630 hits)
 Share this Article
 
Posted by Prabu Arumugam on Aug-03-2010
Languages: C#, Silverlight

This article explains how to create a simple free-hand drawing application in Silverlight, similar to Microsoft Paint. The techniques explained are implemented for demonstration purpose and the source code can be downloaded below.

Freehand Drawing Demo in Silverlight

The techniques explained are implemented for demonstration purpose and the source code of this demonstration is available for download below.

Defining the Canvas

First, a Canvas control is created; the user will be drawing on the surface of this canvas. The freehand drawing is rendered by capturing the mouse movement while the user draws the picture. A picture contains one or more strokes. The stroke is defined as the locus of the mouse from mouse-down to the next mouse-up position; where the locus is the set of all points or lines generated in a stroke. The mouse movements are captured using three mouse events of Canvas control, namely MouseLeftButtonDown, MouseMove and MouseLeftButtonUp.

The canvas is defined as follows:

<Canvas x:Name="MainCanvas"
        Cursor="Stylus"
        MouseLeftButtonDown="MainCanvas_MouseLeftButtonDown"
        MouseMove="MainCanvas_MouseMove"
        MouseLeftButtonUp="MainCanvas_MouseLeftButtonUp">
</Canvas>

Drawing in Canvas Control

The mouse events are defined as below. A boolean variable named drawing is used to recognize the mouse movements (over the canvas) after the drawing of a stroke is started. When the user starts to draw a stroke, this boolean is set to true and it is cleared when the user has finished drawing the stroke. During drawing, whenever a mouse movement is captured, a Line is created and appended to the canvas. A series of continuous / disjoint lines forms a stroke.

private bool drawing = false;
private Point start;

private void MainCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    drawing = true;
    start = e.GetPosition((UIElement)sender);
}

private void MainCanvas_MouseMove(object sender, MouseEventArgs e)
{
    if (drawing)
    {
        Point current = e.GetPosition((UIElement)sender);

        Line line = new Line() { X1 = start.X, Y1 = start.Y, X2 = current.X, Y2 = current.Y };
        line.Stroke = new SolidColorBrush(Colors.Black);
        MainCanvas.Children.Add(line);

        start = current;
    }
}

private void MainCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    drawing = false;
}

 Downloads for this article
File Language Tools
Paint-Demo-Source  23.3 kb  (397 downloads) C#, Silverlight 3 Visual Studio 2008

 Share this Article

 Comments on this Article
Comment by emre on Oct-30-2013
thanks
Comment by nooglesoft on Jan-08-2012
thanks , grate post
 Post your comment here
Your Name
Your Email
Comment
Post Comment

About      Terms      Contact