Monday, August 16, 2010

How to Draw a shape in Silverlight 3

In Silverlight, some time we need to draw shapes. and to draw these shapes we need mouse coordinates while mouse button is down, Up and most important while mouse is moving to give illusion that shape is creating. to do this first Add a static shape (circle, rectangle etc) on canvas and set its visibility to Hidden. after this follow the following code.

Create four Global Variables to store coordinates.

double x1 = 0.0;
double y1 = 0.0;
double x2 = 0.0;
double y2 = 0.0;

Now in Canvas_ MouseLeftButtonDown Event of Mouse get the start points like this

x1 = e.GetPosition(canvas).X;
y1 = e.GetPosition(canvas).Y;
_down = true;

In Canvas_MouseMove event write this code

if ((_down)
{
double xo = e.GetPosition(canvas).X;
double yo = e.GetPosition(canvas).Y;
///// Now set position of that shape (circle, rectangle etc).

Shape.SetValue(Canvas.LeftProperty, Math.Min(xo, x1));
Shape.SetValue(Canvas.TopProperty, Math.Min(yo, y1));

//////Set Shape Size
Shape.Width = Math.Abs(xo - x1);
Shape.Height = Math.Abs(yo - y1);

if (Shape.Visibility != Visibility.Visible)
Shape.Visibility = Visibility.Visible;
}

and Finally in Canvas_MouseLeftButtonUp Event write this code
_down = false;
x2 = e.GetPosition(canvas).X;
y2 = e.GetPosition(canvas).Y;
DrawShape(x1, y1, x2, y2);

I'll explain and provide the Draw function code in my next article.

Happy Coding :)

No comments:

Post a Comment