我已经阅读了所有我能找到但无法解决的问题。我的目标是从 中捕获笔画InkCanvas
并将其转换为Path
. 从路径中,将 a 返回BitmapImage
到Image
控件并将控件放置在Image
上的任意位置InkCanvas
。
如果我写在InkCanvas
“< >”上,我会得到以下结果:
- 只有笔划的左侧“<”显示为位图。(看不到“>”)。
- “<”之外的区域是黑色的——不透明。
- 我想不出一种简单的方法来将路径减少为仅绘制的笔画。即,我看不到如何裁剪绘制的“<>”上方和左侧的空间。
在窗口中,这是我操作的代码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;
}