无法在InkCanvas上定位BitmapImage

本文关键字:定位 BitmapImage InkCanvas | 更新日期: 2023-09-27 18:05:14

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

如果我在InkCanvas上写a "<>",我得到以下结果:

  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;
    }

无法在InkCanvas上定位BitmapImage

Replace

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

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

InkCanvas不继承Canvas并且暴露了它自己的附加属性。你需要调用InkCanvas方法而不是Canvas方法