0

我已经阅读了所有我能找到但无法解决的问题。我的目标是从 中捕获笔画InkCanvas并将其转换为Path. 从路径中,将 a 返回BitmapImageImage控件并将控件放置在Image上的任意位置InkCanvas

如果我写在InkCanvas“< >”上,我会得到以下结果:

  1. 只有笔划的左侧“<”显示为位图。(看不到“>”)。
  2. “<”之外的区域是黑色的——不透明。
  3. 我想不出一种简单的方法来将路径减少为仅绘制的笔画。即,我看不到如何裁剪绘制的“<>”上方和左侧的空间。

在窗口中,这是我操作的代码Image

    void MakeFigure_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        ShapeMaker shapemaker = new ShapeMaker();
        System.Windows.Shapes.Path myshape = shapemaker.StrokesToPath(InkCanvas.Strokes);
        InkCanvas.Strokes.Clear();

        Image image = new Image();
        ImageSource img = shapemaker.PathToBitmapImage(myshape);
        image.Source = img;
        image.Width = img.Width;
        image.Height = img.Height;
        InkCanvas.Children.Add(image);
        InkCanvas.SetLeft(image, 800);
        InkCanvas.SetTop(image, 400);
    }

    public Path StrokesToPath(StrokeCollection strokeCollection)
    {
        Path path = new Path();
        PathGeometry pathGeo = new PathGeometry();

        foreach (Stroke stroke in strokeCollection)
        {
            StylusPointCollection strokepoints = stroke.StylusPoints;

            PathFigure pathFig = new PathFigure();
            pathFig.StartPoint = new Point(strokepoints[0].X, strokepoints[0].Y);

            for (int i = 1; i < strokepoints.Count; i++)
            {
                pathFig.Segments.Add( new LineSegment()
                {
                     Point = new Point(strokepoints[i].X, strokepoints[i].Y)
                });
            }

            pathGeo.Figures.Add(pathFig);
        }

        path.Data = pathGeo;
        path.Stroke = Brushes.White;       
        path.StrokeThickness = 4;           

       return path;
    }

    public BitmapImage PathToBitmapImage(Path path)
    {
       var bounds = path.Data.GetRenderBounds(null);
       path.Measure(bounds.Size);
       path.Arrange(bounds);

        RenderTargetBitmap rtb = new RenderTargetBitmap(
          (int)bounds.Width *4 , (int)bounds.Height*4 , 96, 96, PixelFormats.Pbgra32);
        rtb.Render(path);

        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
        BitmapImage bi = new BitmapImage();

        encoder.Frames.Add(BitmapFrame.Create(rtb));

        using (var stream = new System.IO.MemoryStream())
        {
            encoder.Save(stream);
            stream.Seek(0, System.IO.SeekOrigin.Begin);

            bi.BeginInit();
            bi.CacheOption = BitmapCacheOption.OnLoad;
            bi.StreamSource = stream;
            bi.EndInit();
            bi.Freeze();
        }

        return bi;
    }
4

1 回答 1

0

代替

Canvas.SetLeft(image, 800);
Canvas.SetTop(image, 400);

InkCanvas.SetLeft(image, 800);
InkCanvas.SetTop(image, 400);

InkCanvas 不继承自 Canvas并公开它自己的附加属性。因此,您需要调用 InkCanvas 方法而不是 Canvas 方法。

于 2014-05-25T08:26:52.517 回答