0

如果这是重复的,很多人道歉。我正在将许多 BitmapImages 写入这样的画布的特定部分(片段)。它工作正常:

  TreeFile = "pack://application:,,,/Images/" + TreeFile;

                        var image = new Image
                        {
                            Source = new BitmapImage(new Uri(TreeFile))
                        };
                        image.Width = 10;
                        image.Height = 10;

                        Canvas.SetLeft(image, x );
                        Canvas.SetTop(image, y );
                        MainCanvas.Children.Add(image);

我想要做的是同时复制imageWriteableBitmap BlankMap;同一位置(MainCanvas 和 BlankMap 大小相同)。这是为了创建一个“撤消”。然后,假设用户希望将新的合成图像副本保留BlankMap到最终版本。BitmapImage WorkingMap;最后,我需要将现在完成的图像保存WorkingMap到磁盘。

所以我的问题是:

  1. 使用 WriteableBitmaps 是正确的方法吗?
  2. image我将如何写信BlankMap
  3. BlankMap我将如何写信WorkingMap(尽管 #2 和 #3 可能是相同的问题/答案。

谢谢!如果这是某种形式的重复问题,再次道歉。

4

2 回答 2

1

根据我使用映射工具的经验,我担心您正在应用一种在 WinForms 中有意义并在 WPF 中导致问题的思维过程。请小心在 WPF 中生成的图像,因为它们很容易由于框架中长期存在的错误而泄漏内存。

问题 #1

这是执行“撤消”功能的正确方法吗?不会。但是,WPF 允许您非常轻松地添加、移动和删除元素。

我相信您可以设想您将使用命令来实现您的更改,然后在您想要撤消它时从堆栈中撤消命令。但是,我还没有看到任何有意义的例子。

问题2

当您WriteableBitmap使用现有的初始化 a 时ImageSource,您只需通过在构造函数中传递它来初始化它:

var BlankMap = new WriteableBitmap(image);

之后,您将按照类文档中列出的代码示例进行操作。

问题 #3

你会扭转这个过程。


最重要的是,听起来您想要进行某种图形编辑。位图在 WinForms 中工作得很好,所以很容易让人相信它们在 WPF 中也能工作得一样好。他们不。如果您将位图的使用限制为仅显示,那么您将更容易处理内存泄漏等问题。

于 2017-03-03T13:08:31.903 回答
0

这对我有用:

    public static void CopyImageTo(Image sourceImage, int x, int y, WriteableBitmap target)
    {
        BitmapSource source = sourceImage.Source as BitmapSource;

        int sourceBytesPerPixel = GetBytesPerPixel(source.Format);
        int sourceBytesPerLine = source.PixelWidth * sourceBytesPerPixel;

        byte[] sourcePixels = new byte[sourceBytesPerLine * source.PixelHeight];
        source.CopyPixels(sourcePixels, sourceBytesPerLine, 0);

        Int32Rect sourceRect = new Int32Rect(x, y, source.PixelWidth, source.PixelHeight);
        target.WritePixels(sourceRect, sourcePixels, sourceBytesPerLine, 0);
    }

    public static int GetBytesPerPixel(PixelFormat format)
    {
        return format.BitsPerPixel / 8;
    }
于 2019-12-19T17:21:03.583 回答