I have read all that I can find and can't solve this. My goal is to capture strokes from the InkCanvas
and convert these into a Path
. From the path, return a BitmapImage
to an Image
control and place the Image
control at an arbitrary position on the InkCanvas
.
If I write on the InkCanvas
a "< >", I get the following result:
- Only the left "<" of the strokes is shown as a bitmap. (don't see the ">").
- The area outside of the "<" is BLACK -- not transparent.
- I can't figure a simple way of reducing the Path to just the drawn strokes. i.e., I can't see how to clip the space above and to the left of the drawn "<>".
From the window, this is my code to manipulate the 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;
}