CodeSnips

Sunday, September 20, 2015

WPF Simple Canvas Drawing

I'm brushing up on 3D mathematics and I find it useful (indeed necessary)  to write small bits of code to help understand and visualize the material. I even had a bit of fun writing a few programs in BASIC on a C64 that's part of my vintage computer collection.

Still, having modern tools, it's generally more useful to write graphic programs for more modern displays.  I whipped up the following code to display the results of a parametric circle equation. The tool of choice in this case was LinqPad. I like Linqpad because it's nice for writing and running short code snippets.

I think for many programmers WPF (Windows Presentation Framework) seems to be a complex tool, but, surprisingly, it's relatively simple to whip up simple interfaces using only code.  For this I decided to use the Canvas, Line, and Ellipse shape primitives to create a quick graphic display like this:.
void Main()
{
 var g = new Grid();
 var w = new Window { Width = 420, Height = 440, 
                             Title = "Graph", Content = g};
 var c = new Canvas { Background = Brushes.BlanchedAlmond };

 DrawLine(200,10,200,390,c);
 DrawLine(10,200,390,200,c);
 
 for (int i=0; i<50; i++)
 {
     double t = (1.0 / 50.0) * (i);
  int x = (int) (Math.Cos( 2 * Math.PI * t) * 100) + 197;
  int y = (int) (Math.Sin( 2 * Math.PI * t) * 100) + 197;
  DrawPoint(x,y,c);
 }
 
 g.Children.Add(c);
    w.ShowDialog();
 
}

public void DrawPoint(int x, int y, Canvas c)
{
    var e = new Ellipse { Height = 6, Width = 6, 
                          Fill = Brushes.Blue, Stroke = Brushes.Black };
 Canvas.SetLeft(e,x);
 Canvas.SetTop(e,y);
 c.Children.Add(e);
}

public void DrawLine(int x1, int y1, int x2, int y2, Canvas c)
{
    var l = new Line{ X1 = x1, Y1 = y1, X2 = x2, Y2 = y2, 
                      Stroke = Brushes.Black, StrokeThickness = 1 };
 c.Children.Add(l);
}

No comments:

Post a Comment