[英]How to copy an Image into a section of a WriteableBitmap (C# & WPF)
如果这是重复的,很抱歉。 我正在将一些 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 可能是相同的问题/答案。谢谢! 如果这是某种形式的重复问题,再次道歉。
根据我使用映射工具的经验,我担心您正在应用一个在 WinForms 中有意义的思考过程并导致 WPF 出现问题。 请小心 WPF 中生成的图像,因为它们很容易由于框架深处长期存在的错误而导致内存泄漏。
问题#1
这是执行“撤消”功能的正确方法吗? 不可以。但是,WPF 允许您非常轻松地添加、移动和删除元素。
我相信你会使用命令来实现你的更改,然后在你想撤消它时从堆栈中废除一个命令。 但是,我还没有看到任何有意义的例子。
问题2
当您使用现有的ImageSource
初始化WriteableBitmap
时,您只需将其传递到构造函数中即可对其进行初始化:
var BlankMap = new WriteableBitmap(image);
之后,您将遵循类文档中列出的代码示例。
问题#3
你会逆转这个过程。
最重要的是,听起来您想要进行某种图形编辑。 位图在 WinForms 中效果很好,所以很容易让人相信它们在 WPF 中也能很好地工作。 他们不。 如果您将位图的使用限制为仅显示,那么您将更容易处理内存泄漏等问题。
这对我有用:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.