.:: CODE SNIPPET ::.

"Your time is limited, so don't waste it living someone else's life"

How to draw something on canvas in C#


1. Create a canvas frame
In design screen of WPF, you create a canvas frame like the image below:
canvas
Don’d forget to name canvas frame to Name=”canvas”
Now, we practice to draw a line and a ellipse on the above canvas
2. Draw a line
The ways to draw shapes on canvas are similar to each other.

  • First, you have to define an instance of that shape.
  • Second, you initiate some obligation attributes for that object, for detail they are coordination, width, height, and color.
  • Final, you import that shape into canvas children list.

Let’s begin with a Line

private Line line;
private void init()
{
            line= new Line();
            line.Stroke = new SolidColorBrush(Colors.Black);
            line.StrokeThickness = 2;
            //the head point of the line
            line.X1 = 150;
            line.Y1 = 150;
            //the tail point of the line
            line.X2 = 250;
            line.Y2 = 350;
            //add to canvas children list
            canvas.Children.Add(line);
}

3. Draw an ellipse
The same way for the ellipse

private Ellipse ellipse;
private void init()
{
            ellipse= new Ellipse();
            //the border line of ellipse
            bigCircle.Stroke = new SolidColorBrush(Colors.Blue);
            //fill the ellipse
            ellipse.Fill = new SolidColorBrush(Colors.Green);
            ellipse.Width = 150;
            ellipse.Height = 150;
            Canvas.SetTop(ellipse, 10);
            Canvas.SetLeft(ellipse, 10);
            canvas.Children.Add(ellipse);
}

Now we have both line and ellipse on the canvas. Now if you want to clear that canvas for redrawing or some other purposes. You can use:

canvas.Children.Clear();
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

%d bloggers like this: