Draw Dynamic Polygons In WPF

Even though Microsoft provided lots of controls as well as 3rd parties, we still need to draw dynamic graphics, sometimes. I need to draw vector image based on input file which is just a series of x-y coordinates. Normalization and rescaling are not a problem but I didn't know how to draw it like GDI/GDI+ time.
In GDI+ we can draw things like

Graphics g = Graphics.FromImage(mf);
g.DrawLine(Pens.Blue, new Point(10, 10), new Point(100, 100));

But, WPF canvas is a collection of children objects. It's not a bitmap anymore.
So, we need to change our idea about drawings in here.
First off, a line object needs to be created.

using System.Windows.Shape;
using System.Windows.Media;
...
Line line = new Line();
line.Stroke = Brushes.LightSteelBlue;
line.StrokeThickness = 2;
line.X1 = 10;
line.Y1 = 10;
line.X2 = 100;
line.Y2 = 100;

Now, we can attach this to a container control. Let's add it onto a canvas. Alignments should be considered depends on the type of the container control.

line.HorizontalAlignment = HorizontalAlignment.Left;
line.VerticalAlignment = VerticalAlignment.Center;
freeCanvas.Children.Add(line);

Same way, a polygon can be added

Polygon p = new Polygon();
p.Stroke = Brushes.Black;
p.Fill = Brushes.LightBlue;
p.StrokeThickness = 1;
p.HorizontalAlignment = HorizontalAlignment.Left;
p.VerticalAlignment = VerticalAlignment.Center;
p.Points = new PointCollection() { new Point(10, 10), new Point(100, 100), new Point(200, 200) };
freeCanvas.Children.Add(p);

Pretty easy, huh! Interesting thing is that you can change any property of a Shape object after attaching it to the parent control and we can see the change without forcing to invalidate screen.
We can even hook up event handler to a Shape object to make dynamic behavior which reacts by a user input.

p.PreviewMouseDown += new MouseButtonEventHandler(Polygon_MouseDown);
p.MouseUp += new MouseButtonEventHandler(Polygon_MouseUp);
...
protected void Polygon_MouseDown(object sender, MouseButtonEventArgs e)
{
  (sender as Shape).Fill = Brushes.Red;
}
protected void Polygon_MouseUp(object sender, MouseButtonEventArgs e)
{
  (sender as Shape).Fill = Brushes.LightBlue;
}
...

Interesting! Since everything is a real object, we don't need to worry about redraw whenever UI's updated.
System.Windows.Shapes namespace has Ellipse, Line, Path, Polygon, Polyline, Rectangle as well as Shape as based class.
Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License