【问题标题】:Render an Image from a StrokeCollection in c#从 C# 中的 StrokeCollection 渲染图像
【发布时间】:2021-01-30 21:54:22
【问题描述】:

我需要从 StrokeCollection 中获取图像,但由于 mvvm 结构,我无法访问 Visual (InkCanvas) 本身。有没有一种简单的方法可以完成这项工作?

XAML:

<InkCanvas x:Name="paintSurface" Grid.Row="0" Opacity="0.2" Strokes="{Binding Strokes}">
    <InkCanvas.DefaultDrawingAttributes>
        <DrawingAttributes Color="Black" Width="10" Height="10"/>
    </InkCanvas.DefaultDrawingAttributes>
</InkCanvas>

视图模型:

private StrokeCollection _strokes;
public StrokeCollection Strokes {
    get => _strokes;
    set => SetProperty(ref _strokes, value);
} 

现在我只想将 StrokeCollection 转换为某种形式的可处理图像,它是 Bitmap、BitmapImage、Mat、EmguCV Image,并不重要。 提前谢谢:)

【问题讨论】:

  • 你看过这篇文章了吗? stackoverflow.com/questions/49231819/…
  • 你可以在视图中渲染targetbitmap。您“只”需要从视图模型触发它或告诉视图模型它已经完成。无论如何,您可能不想对一大块 ui 进行自动化测试,但是如果您想重新使用它,您可以将代码封装在一个行为中。你需要图片吗?您可以从笔划中提取点并构建几何用作路径数据。

标签: c# wpf image inkcanvas


【解决方案1】:

我通过将 StrokeCollection 交给一个助手类解决了我的问题,我在其中创建了一个新的 InkCanvas,添加了 Strokes(来自 UI 中的原始 InkCanvas)并渲染它。

public static Bitmap convertStrokestoImage(StrokeCollection strokes, int width, int height)
    {
        InkCanvas InkyStinky = new InkCanvas();
        InkyStinky.RenderSize = new System.Windows.Size(width, height);
        InkyStinky.Strokes.Add(strokes);
        RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
        bmp.Render(InkyStinky);
        MemoryStream stream = new MemoryStream();
        BitmapEncoder encoder = new BmpBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bmp));
        encoder.Save(stream);
        Bitmap b = new Bitmap(stream);
        return b;
    }

【讨论】:

    【解决方案2】:

    这是你的答案。 将 StrokeCollection 保存为所有格式的图像。
    https://stackoverflow.com/a/51207941/7300644

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-13
      • 2017-11-15
      • 2012-09-10
      • 2011-08-07
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多