Wednesday, July 27, 2011

Drawing in WPF

The concept of drawing in WPF is quite different with that in .net form. There is no Graphics object to handle the drawing process, you need to new Shape objects (Line, Ellipse, Rectangle, ...) into a Canvas as follow,

1. New a Canvas

In XAML file

<Canvas Margin="0,0,0,0" Name="c"/>

or in C# source file

Canvas c = new Canvas();
this.Content = c;

2. New Shape objects and put them into Canvas

private void DrawLine(Canvas c, Point s, Point e)
{
/// new a line geometry
LineGeometry l = new LineGeometry(s, e);

/// new a path and set its data as the geometry
System.Windows.Shapes.Path p =
new System.Windows.Shapes.Path();
p.Data = l;

/// add the line as a child of canvas
c.Children.Add(p);
}

LineGeometry above can also be replaced with EllipseGeometry or RectangleGeometry to draw an ellipse or a retangle. Besides, WPF will redraw automatically, so just add the objects. And all objects in Canvas is still programalbe.

--
Reference
WPF幾何繪圖
WPF中,如何使用圖像API進行繪製

No comments:

Post a Comment