WPF绘制矢量图形并绑定到界面的方法

这里先封装一个方法,使用的时候先创建一个Draw,拿到DrawingContext 之后就可以通过DrawingContext 去绘制想要的图形,绘制完成后通过GetDraw拿到所有绘制的结果
添加一个PrintImage()用于测试当前绘图的样子用于测试

   public class DrawVector
   {
       public DrawingVisual? visual { get; set; }

       public DrawingContext CreateDraw()
       {
           if (visual == null)
               visual = new DrawingVisual();
           var dc = visual.RenderOpen();

           return dc;
       }

       public DrawingGroup? GetDraw(DrawingContext? dc)
       {
           if (visual == null)
               return null;
           if (dc == null)
               return null;

           Dispose(dc);
           var draw = visual.Drawing.Frozen();
           //PrintImage();

           return draw;

       }

       /// 
       /// 测试打印绘图结果
       /// 
       private void PrintImage()
       {
           var bmp = new RenderTargetBitmap(2000, 2000, 96, 96, PixelFormats.Pbgra32);
           bmp.Render(visual);
           var encoder = new PngBitmapEncoder();
           encoder.Frames.Add(BitmapFrame.Create(bmp));

           using (var stream = new FileStream($"D:\\{Guid.NewGuid()}.png", FileMode.Create))
           {
               encoder.Save(stream);
           }
       }

       public void RotationAngle(DrawingContext dc, Rect rect, double angleInDegrees)
       {
           var rotateTransform = new RotateTransform(angleInDegrees, rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
           dc.PushTransform(rotateTransform);
       }

       private void Dispose(DrawingContext? dc)
       {
           if (dc != null)
               dc.Close();
       }

   }

使用实例

   var drawVector = new DrawVector();
   var dc = drawVector.CreateDraw();
   
   dc.DrawRectangle(System.Windows.Media.Brushes.White, new System.Windows.Media.Pen(System.Windows.Media.Brushes.White, 1).Frozen(), new Rect(0, 0, MapBackCanvasWidth, MapBackCanvasHeight));
   DrawVectorContent(dc);

   return drawVector.GetDraw(dc);

你可能感兴趣的:(C#,wpf)