在winform 中我们使用GDI+ 进行绘图,到了WPF, 使用的是DirectX渲染,所以不能使用GDI+ 进行绘图,
但是其实WPF中也是有绘图单元的,本文用DrawingVisual 来进行基础的绘图,在一张图片上进行画正弦信号图:
先从Image类继承一个绘图的单元: public class DrawingImage:Image { private List<Visual> visuals = new List<Visual>(); protected override Visual GetVisualChild(int index) { return visuals[index]; } protected override int VisualChildrenCount { get { return visuals.Count; } } public void AddVisual(Visual visual) { visuals.Add(visual); base.AddVisualChild(visual); base.AddLogicalChild(visual); } public void DeleteVisual(Visual visual) { visuals.Remove(visual); base.RemoveVisualChild(visual); base.RemoveLogicalChild(visual); } public DrawingVisual GetVisual(Point point) { HitTestResult hitResult = VisualTreeHelper.HitTest(this, point); return hitResult.VisualHit as DrawingVisual; } private List<DrawingVisual> hits = new List<DrawingVisual>(); public List<DrawingVisual> GetVisuals(Geometry region) { hits.Clear(); GeometryHitTestParameters parameters = new GeometryHitTestParameters(region); HitTestResultCallback callback = new HitTestResultCallback(this.HitTestCallback); VisualTreeHelper.HitTest(this, null, callback, parameters); return hits; } private HitTestResultBehavior HitTestCallback(HitTestResult result) { GeometryHitTestResult geometryResult = (GeometryHitTestResult)result; DrawingVisual visual = result.VisualHit as DrawingVisual; if (visual != null && geometryResult.IntersectionDetail == IntersectionDetail.FullyInside) { hits.Add(visual); } return HitTestResultBehavior.Continue; } }
XAML页面中使用 <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication1" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Grid x:Name="Main"> <local:DrawingImage x:Name="panel" Source="Tulips.png" Stretch="Fill"></local:DrawingImage> </Grid> </Window>
后台添加绘图程序: public MainWindow() { InitializeComponent(); DrawingVisual visualx = new DrawingVisual(); using (DrawingContext dc = visualx.RenderOpen()) { dc.PushOpacity(0.8); dc.PushOpacityMask(Brushes.Red); Pen pen = new Pen(Brushes.Green, 2); for (int i = 0; i < 500; i ++) { dc.DrawLine(pen, new Point(i*2, Math.Sin(i*0.1)*100 + 200), new Point((i + 1)*2, Math.Sin((i + 1)*0.1)*100 + 200)); dc.DrawText(new FormattedText("Hello, World!", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Arial"), 10, Brushes.CornflowerBlue), new Point(i * 2, Math.Sin(i * 0.1) * 100 + 200)); } } panel.AddVisual(visualx); }
看下效果: