比几何和路径消耗的资源更小,适合大量。
drawingContext.DrawRectangle();
drawingContext.DrawText();
drawingContext.DrawEllipse();
drawingContext.DrawGeometry();
drawingContext.DrawRoundedRectangle();
drawingContext.DrawImage();
DrawingVisual visual = new DrawingVisual(); using (DrawingContext drawingContext = visual.RenderOpen()) { Pen pen = new Pen(Brushes.Black, 3); drawingContext.DrawLine(pen, new Point(0, 50), new Point(50, 0)); drawingContext.DrawLine(pen, new Point(50, 0), new Point(100, 50)); drawingContext.DrawLine(pen, new Point(0, 50), new Point(100, 50)); }
绘制可视化对象
class MyPanel: Panel { private List<Visual> visuals = new List<Visual>(); protected override Visual GetVisualChild(int index) { return visuals[index]; } protected override int VisualChildrenCount => visuals.Count; public void AddVisual(Visual visual) { visuals.Add(visual); base.AddLogicalChild(visual); base.AddVisualChild(visual); } }
元素中包含可视化对象
private void MyPanel_Loaded(object sender, RoutedEventArgs e) { DrawingVisual visual = new DrawingVisual(); using (DrawingContext drawingContext = visual.RenderOpen()) { Brush brush = Brushes.LightGreen; Pen pen = new Pen(Brushes.SteelBlue, 3); drawingContext.DrawLine(pen, new Point(0, 50), new Point(50, 0)); drawingContext.DrawLine(pen, new Point(50, 0), new Point(100, 50)); drawingContext.DrawLine(pen, new Point(0, 50), new Point(100, 50)); drawingContext.DrawRectangle(brush, pen, new Rect(new Point(100, 100), new Size(50, 100))); drawingContext.DrawEllipse(brush,pen,new Point(300,200),100,60); } MyPanel.AddVisual(visual); }