如何直接在图像上绘制?

How to draw directly on an Image?

我有一个以像素为单位绘制的小程序。它实际上工作正常,但每次它通过我的计时器更新图像时,我都会注意到闪烁。我认为这是由于总是设置一个新的来源,所以我的问题是:是否有一种方法可以直接在图像上绘制而不是设置一个新的来源?

这是我的绘制方法:

private void SetPixel(int x, int y)
{
    WriteableBitmap wrb = new WriteableBitmap((BitmapSource)image.Source);

    byte[] color = new byte[] { b, g, r, a };

    wrb.WritePixels(new Int32Rect(x, y, 1, 1), color, 4, 0);

    image.Source = wrb;
}

您可以尝试将 Source 属性 转换为 WriteableBitmap 而不是每次都将其设置为新的 WriteableBitmap:

private void SetPixel(int x, int y)
{
    WriteableBitmap wrb = image.Source as WriteableBitmap;
    if (wrb == null)
    {
        wrb = new WriteableBitmap((BitmapSource)image.Source);
        image.Source = wrb;
    }
    byte[] color = new byte[] { b, g, r, a };
    wrb.WritePixels(new Int32Rect(x, y, 1, 1), color, 4, 0);
}