如何使用 canvas 内容作为位图?

How to use canvas content as a bitmap?

我正在 WPF 中编写绘图应用程序,当我想要制作颜色选择器或填充工具时遇到问题。我不知道如何使用 canvas 内容作为位图,我发明的唯一解决方案是保存它,然后作为位图打开然后我可以轻松地对像素进行操作以获取和设置像素,但我想用另一种方式来做.有什么建议吗?

如果您正在寻找将 canvas UIElement 转换为 BitmapSource 以便对其进行操作,那么您可以在 MSDN MSDN 上查看此 post。

这是从您的 canvas 获取 BitmapSource 的辅助函数:

public static BitmapSource CreateBitmapSourceFromVisual(
    Double width,
    Double height,
    Visual visualToRender,
    Boolean undoTransformation)
{
    if (visualToRender == null)
    {
        return null;
    }
    RenderTargetBitmap bmp = new RenderTargetBitmap((Int32)Math.Ceiling(width),                                                        (Int32)Math.Ceiling(height), 96,96, PixelFormats.Pbgra32);

    if (undoTransformation)
    {
        DrawingVisual dv = new DrawingVisual();
        using (DrawingContext dc = dv.RenderOpen())
        {
            VisualBrush vb = new VisualBrush(visualToRender);
            dc.DrawRectangle(vb, null, new Rect(new Point(), new Size(width, height)));
        }
        bmp.Render(dv);
    }
    else
    {
        bmp.Render(visualToRender);
    }
  return bmp;
}

由于颜色选择器或填充工具的问题,我没有得到想要说的内容,所以我无法帮助您。祝你好运!