wpf内置提供了Ellipse等标签画图形,不仅如此而且还提供了许多的事件(因为其继承自FrameworkElement).
在某些情况下,我们可以不采用这些标签
仅仅用于呈现,并不复杂的操作(没有事件).
DrawingVisual是一个轻量绘图类,在上述情况成立下可以采用DrawingVisual类来绘图提高性能.
方法如下
1.使用DrawingVisual必须创建一个容器(从FrameworkElement继承创建一个容器)
public class MyVisualHost : FrameworkElement
{
}
{
}
2.创建一个全局可视对象的集合(VisualCollection)
private VisualCollection _children;
public MyVisualHost()
{
_children = new VisualCollection(this);
}
public MyVisualHost()
{
_children = new VisualCollection(this);
}
3.创建DrawingVisual
先初始化一个DrawingVisual类,然后使用RenderOpen()获取其DrawingContext 对象(DrawingContext 不可以以new方式初始化),DrawingContext 提供了一些以Draw开头的绘图方法,绘制完成以后必须调用Close方法(不然不会呈现)
private DrawingVisual CreateDrawingVisualRectangle()
{
DrawingVisual drawingVisual = new DrawingVisual();
// Retrieve the DrawingContext in order to create new drawing content.
DrawingContext drawingContext = drawingVisual.RenderOpen();
// Create a rectangle and draw it in the DrawingContext.
Rect rect = new Rect(new Point(160, 100), new Size(320, 80));
drawingContext.DrawRectangle(Brushes.LightBlue, (Pen)null, rect);
// Persist the drawing content.
drawingContext.Close();
return drawingVisual;
}
{
DrawingVisual drawingVisual = new DrawingVisual();
// Retrieve the DrawingContext in order to create new drawing content.
DrawingContext drawingContext = drawingVisual.RenderOpen();
// Create a rectangle and draw it in the DrawingContext.
Rect rect = new Rect(new Point(160, 100), new Size(320, 80));
drawingContext.DrawRectangle(Brushes.LightBlue, (Pen)null, rect);
// Persist the drawing content.
drawingContext.Close();
return drawingVisual;
}
DrawingContext还包含一些以Push开头的方法,可以为图形设置透明度,effect等。看sdk就ok了,记录下
另外使用DrawingGroup也可以,不过容器变成了Image
// Display the drawing using an image control.
Image theImage = new Image();
DrawingImage dImageSource = new DrawingImage(dGroup);
theImage.Source = dImageSource;
panel.Children.Add(theImage);
Image theImage = new Image();
DrawingImage dImageSource = new DrawingImage(dGroup);
theImage.Source = dImageSource;
panel.Children.Add(theImage);