我有一个WriteableBitmap,我想反复澄清和重新绘制。
我已经看到了直接写入像素数组的引用,但是在WriteableBitmap中不能访问像素数组。我也尝试过每次重新创建WriteableBitmap的建议,但我的应用程序几乎立即耗尽了内存。
有简单的方法来清除WriteableBitmap吗?
发布于 2014-05-15 09:20:46
要使用writeablebitmap.clear(),您需要WriteableBitmapEx库。http://writeablebitmapex.codeplex.com
发布于 2014-12-12 18:28:44
我们阻止将空白字节数组复制到可写位图的后缓冲区以完成此操作。我们也可以复制原始帧超过30帧每秒1k x 1k位图。
两个例子快速或安全(而且仍然相当快)。我更喜欢不安全的版本。
#region External
[DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")]
public static extern void CopyMemory(IntPtr destination, IntPtr source, uint length);
#endregion
private const int PixelHeight = 1024;
private const int PixelWidth = 1024;
private const int DpiHeight = 96;
private const int DpiWidth = 96;
private const int RgbBytesPerPixel = 3;
WriteableBitmap _myBitmap = new WriteableBitmap(PixelHeight, PixelWidth, DpiHeight, DpiWidth, PixelFormats.Rgb24, null);
private readonly byte[] _blankImage = new byte[PixelHeight * PixelWidth * RgbBytesPerPixel];
private unsafe void FastClear()
{
fixed (byte* b = _blankImage)
{
CopyMemory(_myBitmap.BackBuffer, (IntPtr)b, (uint)_blankImage.Length);
Application.Current.Dispatcher.Invoke(() =>
{
_myBitmap.Lock();
_myBitmap.AddDirtyRect(new Int32Rect(0, 0, _myBitmap.PixelWidth, _myBitmap.PixelHeight));
_myBitmap.Unlock();
});
}
}
private void SafeClear()
{
GCHandle pinnedArray = new GCHandle();
IntPtr pointer = IntPtr.Zero;
try
{
//n.b. If pinnedArray is used often wrap it in a class with IDisopsable and keep it around
pinnedArray = GCHandle.Alloc(_blankImage, GCHandleType.Pinned);
pointer = pinnedArray.AddrOfPinnedObject();
CopyMemory(_myBitmap.BackBuffer, pointer, (uint)_blankImage.Length);
Application.Current.Dispatcher.InvokeAsync(() =>
{
_myBitmap.Lock();
_myBitmap.AddDirtyRect(new Int32Rect(0, 0, _myBitmap.PixelWidth, _myBitmap.PixelHeight));
_myBitmap.Unlock();
});
}
finally
{
pointer = IntPtr.Zero;
pinnedArray.Free();
}
}发布于 2017-05-04 08:55:03
CCondron给出的答案最终将开始抛出AccessViolationException。幸运的是,我们能够以一种更简单、更快、更稳定的方式解决这个问题:
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern void RtlZeroMemory(IntPtr dst, int length);
protected void ClearWriteableBitmap(WriteableBitmap bmp)
{
RtlZeroMemory(bmp.BackBuffer, bmp.PixelWidth * bmp.PixelHeight * (bmp.Format.BitsPerPixel / 8));
bmp.Dispatcher.Invoke(() =>
{
bmp.Lock();
bmp.AddDirtyRect(new Int32Rect(0, 0, bmp.PixelWidth, bmp.PixelHeight));
bmp.Unlock();
});
}https://stackoverflow.com/questions/23673733
复制相似问题