如果这是重复的话,很多道歉。 我正在将一些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);
我想要做的是同时将image
复制到WriteableBitmap BlankMap;
并在同一位置(MainCanvas和BlankMap的大小相同)。这是为了创建一个'撤消'。然后,假设用户想要将新的合成图像副本BlankMap
保留到最终BitmapImage WorkingMap;
。最后,我需要将现已完成的WorkingMap
保存到磁盘。
所以我的问题是:
image
写入BlankMap
?BlankMap
写入WorkingMap
(虽然#2和#3可能是相同的问题/答案。谢谢!而且,如果这是某种形式的重复问题,请再次道歉。
答案 0 :(得分:1)
根据我对映射工具的经验,我担心你正在应用一个在WinForms中有意义的思维过程并导致WPF出现问题。请注意WPF中生成的图像,因为它们很容易泄漏内存,因为框架中存在长期存在的错误。
问题#1
这是执行“撤消”功能的正确方法吗?不会。但是,WPF允许您非常轻松地添加,移动和删除元素。
我相信您可以设想使用命令实现更改,然后在要撤消时从堆栈中废除命令。但是,我还没有看到任何有意义的例子。
问题#2
使用现有WriteableBitmap
初始化ImageSource
时,只需在构造函数中传递它即可对其进行初始化:
var BlankMap = new WriteableBitmap(image);
之后,您将按照class documentation。
中列出的代码示例进行操作问题#3
你会改变这个过程。
最重要的是,听起来你想要进行某种形式的图形编辑。位图在WinForms中工作得非常好,所以很容易让人相信它们在WPF中的工作效果会很好。他们不。如果限制使用位图只显示那么你将更容易处理内存泄漏等。
答案 1 :(得分: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;
}