Create Shapes Dynamically in WPF

Introduction

Shapes in WPF

A Shape is a type of UIElement that enables you to draw a shape to the screen. It provides us with a large arsenal of vector graphic types such as Line, Ellipse, Path and others and because they are UI elements, Shape objects can be used inside Panel elements and most controls.

Get started with an example using the
following procedure:

  1. Open Visual Studio 2012
  2. Go to File => New => Project
  3. Choose WPF Application

Go to the MainWindows.xaml file and create a canvas area and Button to design dynamic shapes.

Insert this code

<Window x:Class="WpfShapeApplication.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

         Title="Dynamic Shapes" Height="350" Width="525" WindowStartupLocation="CenterScreen">

    <DockPanel>

        <ToggleButton DockPanel.Dock="Top" Width="100" Name="CreateShape1" Click="CreateShape1_Click" Content="Create Rectangle" />

        <ToggleButton DockPanel.Dock="Top" Width="100" Name="CreateShape2" Click="CreateShape2_Click" Content="Create Circle" />

        <Canvas Background="Gray" Name="canvasArea"

                MouseLeftButtonDown="canvasArea_MouseLeftButtonDown"

                MouseRightButtonDown="canvasArea_MouseRightButtonDown">

        </Canvas>

    </DockPanel>

</Window>

Now go to MainWindows.xaml.cs and replace the existing code with this code:
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

 

namespace WpfShapeApplication

{

    /// <summary>

    /// Interaction logic for MainWindow.xaml

    /// </summary>   

    public partial class MainWindow : Window

    {

        private enum SelectedShape

        { None, Circle, Rectangle }

        private SelectedShape Shape1 = SelectedShape.None;

        public MainWindow()

        {

            InitializeComponent();

        }

        private void CreateShape1_Click(object sender, RoutedEventArgs e)

        {

            Shape1 = SelectedShape.Rectangle;

        }

        private void CreateShape2_Click(object sender, RoutedEventArgs e)

        {

            Shape1 = SelectedShape.Circle;

        }

        private void canvasArea_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)

        {

            Shape Rendershape = null;

            switch (Shape1)

            {

                case SelectedShape.Circle:

                    Rendershape = new Ellipse() { Height = 40, Width = 40 };

                    RadialGradientBrush brush = new RadialGradientBrush();

                    brush.GradientStops.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#FF7689"), 0.250));

                    brush.GradientStops.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#FF7689"), 0.100));

                    brush.GradientStops.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#FF7689"), 8));

                    Rendershape.Fill = brush;

                    break;

                case SelectedShape.Rectangle:

                    Rendershape = new Rectangle() { Fill = Brushes.Blue, Height = 45, Width = 45, RadiusX = 12, RadiusY = 12 };

                    break;

                default:

                    return;s

            }

 

            Canvas.SetLeft(Rendershape, e.GetPosition(canvasArea).X);

            Canvas.SetTop(Rendershape, e.GetPosition(canvasArea).Y);

 

            canvasArea.Children.Add(Rendershape);

        }

 

        private void canvasArea_MouseRightButtonDown(object sender, MouseButtonEventArgs e)

        {

            Point pt = e.GetPosition((Canvas)sender);

            HitTestResult result = VisualTreeHelper.HitTest(canvasArea, pt);

 

            if (result != null)

            {

                canvasArea.Children.Remove(result.VisualHit as Shape);

            }

        }  

    }

}

Code explanation

At the top in the design you see we created two buttons; one for a circle and another for a rectangle, as in the following:

<ToggleButton DockPanel.Dock="Top" Width="100" Name="CreateShape1" Click="CreateShape1_Click" Content="Create Rectangle" />

<ToggleButton DockPanel.Dock="Top" Width="100" Name="CreateShape2" Click="CreateShape2_Click" Content="Create Circle" />


Now for the code behind the main part is a switch/case in which we define two case statements set by a button click as you choose a shape and then click on the canvas, the switch/case is responsible for designing the shape on the canvas when you click the left button of your mouse.
 

switch (Shape1)

            {

                case SelectedShape.Circle:

                    Rendershape = new Ellipse() { Height = 40, Width = 40 };

                    RadialGradientBrush brush = new RadialGradientBrush();

                    brush.GradientStops.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#FF7689"), 0.250));

                    brush.GradientStops.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#FF7689"), 0.100));

                    brush.GradientStops.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#FF7689"), 8));

                    Rendershape.Fill = brush;

                    break;

                case SelectedShape.Rectangle:

                    Rendershape = new Rectangle() { Fill = Brushes.Blue, Height = 45, Width = 45, RadiusX = 12, RadiusY = 12 };

                    break;

                default:

                    return;

            }

Then for the MouseRightButtonDown event when you click on the right button of your mouse your shape will be deleted or removed.

Point pt = e.GetPosition((Canvas)sender);

HitTestResult result = VisualTreeHelper.HitTest(canvasArea, pt);
 

Point pt = e.GetPosition((Canvas)sender);

            HitTestResult result = VisualTreeHelper.HitTest(canvasArea, pt);

 

            if (result != null)

            {

                canvasArea.Children.Remove(result.VisualHit as Shape);

            }

Run your application.

ShapesWPF1.jpg

Now choose you shape what you want to create and left-click on your mouse on the canvas and you will see your selected shape drawn on the canvas.

ShapesWPF2.jpg

Now to delete the shape just put the mouse on the shape and right-click on your mouse and your shape will be deleted.

ShapesWPF3.jpg

Thank you.