【发布时间】:2014-05-25 02:42:06
【问题描述】:
我已经阅读了所有我能找到但无法解决的问题。我的目标是从InkCanvas 中捕获笔画并将它们转换为Path。从路径中,将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;
}
【问题讨论】:
-
我想我找到了问题所在。出于某种原因,Canvas.SetLeft 和 Canvas.SetTop 在我的 InkCanvas 上不起作用,因为我的 inkcanvas 被定义为自定义墨水画布...... CustomInkCanvas 继承自 InkCanvas。如何为 CustomInkCanvas 设置图像?
-
建议编辑回手头的问题。
标签: c# wpf path bitmapimage inkcanvas