下面的简单示例演示如何在将 WriteableBitmap 分配给图像控件的 Source 属性时连续写入它。
XAML 就是这样:
<Window ...>
<Grid>
<Image x:Name="image"/>
</Grid>
</Window>
在后面的代码中有一个计时器,它每秒用随机像素颜色值覆盖 WriteableBitmap 十次。请注意,您必须在 Visual Studio 项目属性(在“生成”选项卡中)中允许不安全代码。
或者Lock
//您也可以调用AddDirtyRect
. 但是,该方法还允许另一个非 UI 线程写入.Unlock
writePixels
Lock
BackBuffer
public partial class MainWindow : Window
{
private readonly WriteableBitmap bitmap
= new WriteableBitmap(100, 100, 96, 96, PixelFormats.Bgr32, null);
public MainWindow()
{
InitializeComponent();
image.Source = bitmap;
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(0.1) };
timer.Tick += OnTimerTick;
timer.Start();
}
private unsafe void OnTimerTick(object sender, EventArgs e)
{
int pixelValue = (int)DateTime.Now.Ticks & 0xFFFFFF;
bitmap.Lock();
var backBuffer = bitmap.BackBuffer;
for (int y = 0; y < bitmap.PixelHeight; y++)
{
for (int x = 0; x < bitmap.PixelWidth; x++)
{
var bufPtr = backBuffer + bitmap.BackBufferStride * y + x * 4;
*((int*)bufPtr) = pixelValue;
}
}
bitmap.AddDirtyRect(new Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight));
bitmap.Unlock();
}
}