我们将使用Shape进行基本图形绘制。
例子
一个可移动的矩形方框:
XAML代码:
后台代码:
private void Window_KeyUp(object sender, KeyEventArgs e){ switch (e.Key) { case Key.Up: RectangleCanvasTop += 10; break; case Key.Down: RectangleCanvasTop -= 10; break; case Key.Right: RectangleCanvasLeft += 10; break; case Key.Left: RectangleCanvasLeft -= 10; break; default: break; } Canvas.SetLeft(DisplayRectangle, RectangleCanvasLeft); Canvas.SetTop(DisplayRectangle, RectangleCanvasTop);}
Shape简介
以下是各类Shape的继承结构:
各类Shape均继承于Shape,而Shape与其它的WPF控件一样,也继承于FrameworkElement,即其它控件支持的功能(各种事件,属性),Shape也是支持的,这是使用Shape绘图的优点。
例子中,Shape是放在Canvas中的,Shape亦可放在其它的Layout控件中。由于Canvas提供了绝对定位的支持,故而常常与Shape搭配出现。
Ellipse:
XAML实现:
后台代码实现:
var circle = new Ellipse(){ Width = 100, Height = 100, Fill = new SolidColorBrush(Colors.White)};var ellipse = new Ellipse(){ Width = 50, Height = 100, Fill = new SolidColorBrush(Colors.White)};Canvas.SetLeft(ellipse, 100);MainCanvas.Children.Add(circle);MainCanvas.Children.Add(ellipse);
Line
XAML实现:
后台代码实现:
MainCanvas.Children.Add(new Line(){ X1 = 0, X2 = 100, Y1 = 100, Y2 = 0, Stroke = new SolidColorBrush(Colors.White)});
Polygon
XAML实现:
后台代码:
var polygon1PointsCollection = new PointCollection();polygon1PointsCollection.Add(new Point() { X = 0, Y = 0 });polygon1PointsCollection.Add(new Point() { X = 50, Y = 50 });polygon1PointsCollection.Add(new Point() { X = 50, Y = 100 });var polygon1 = new Polygon(){ Stroke = new SolidColorBrush(Colors.Black), Points = polygon1PointsCollection};MainCanvas.Children.Add(polygon1);var polygon2PointsCollection = new PointCollection();polygon2PointsCollection.Add(new Point() { X = 0, Y = 0 });polygon2PointsCollection.Add(new Point() { X = 50, Y = 50 });polygon2PointsCollection.Add(new Point() { X = 50, Y = 100 });polygon2PointsCollection.Add(new Point() { X = 100, Y = 50 });var polygon2 = new Polygon(){ Stroke = new SolidColorBrush(Colors.Black), Points = polygon2PointsCollection, Fill = new SolidColorBrush(Colors.White)};Canvas.SetLeft(polygon2, 100);MainCanvas.Children.Add(polygon2);
虚线边框:
XAML实现: