I have a few small WinForms applications written in C# that utilise System.Drawing.Bitmap
and System.Windows.Forms.PictureBox
to display a bitmap from a raw byte buffer that the application maintains over time. In a way, it's akin to poor-man's animation.
I would like to port these applications to WPF but there's a lot of custom logic in the byte buffer writing that I am unwilling to change. After some Googling, I tried using the System.Windows.Media.Imaging.WriteableBitmap
class but couldn't make it work. How is this class supposed to be used and does it fit with my original design?
Here's a snippet from an original WinForms app that cumulatively writes random colors into random positions on a bitmap:
private void Form1_Load(object sender, EventArgs e)
{
_timer.Tick += new EventHandler(Timer_Tick);
_timer.Interval = 25;
_timer.Enabled = true;
}
private void Timer_Tick(object sender, EventArgs e)
{
Animate();
}
private void Animate()
{
Bitmap bitmap = (Bitmap)pictureBox1.Image;
if (bitmap != null)
{
bitmap.Dispose();
}
bitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
var data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
if (_buffer == null)
{
_buffer = new byte[data.Stride * bitmap.Height];
}
for (int i = 0; i < 1000; i++)
{
var x = _random.Next(bitmap.Width);
var y = _random.Next(bitmap.Height);
var red = (byte)_random.Next(byte.MaxValue);
var green = (byte)_random.Next(byte.MaxValue);
var blue = (byte)_random.Next(byte.MaxValue);
var alpha = (byte)_random.Next(byte.MaxValue);
_buffer[y * data.Stride + x * 4] = blue;
_buffer[y * data.Stride + x * 4 + 1] = green;
_buffer[y * data.Stride + x * 4 + 2] = red;
_buffer[y * data.Stride + x * 4 + 3] = alpha;
}
Marshal.Copy(_buffer, 0, data.Scan0, _buffer.Length);
bitmap.UnlockBits(data);
pictureBox1.Image = bitmap;
}