René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Drawing bitmap with threads in .NET

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;

public class BitmapThread : Form {

   BitmapThread() {
     Width=512;
     Height=512;

     this.Load += new System.EventHandler(OnLoad);
     brush      = new SolidBrush(Color.Black);
     random     = new Random();


     //for (int i=0;i<256; i++) {
      // bmp.SetPixel(i,i,Color.FromArgb(255,255-i,i,0));
     //}
   }

/*   protected override void OnPaint(PaintEventArgs e) {
      Graphics g = e.Graphics;

      g.DrawImage(bmp,128,128);
   }*/

   private void OnLoad(object sender, System.EventArgs e) {
     bmp           = new Bitmap(256,256,PixelFormat.Format32bppArgb);
     dc_paint      = Graphics.FromImage(bmp);
     dc_client     = CreateGraphics();
     timer         = new Timer();
     timer.Enabled = true;
     timer.Tick   += new EventHandler(OnTimer);
     timer.Interval= 1000;
   }

   private void OnTimer(object sender, System.EventArgs e) {
      phi -= 6;

      dc_paint.FillRectangle(brush, 0, 0, 256,256);
      dc_paint.DrawLine(new Pen(Color.FromArgb(255,50,80,100)), 128,128,(int)(128+120*Math.Sin(phi/360*Math.PI*2)),(int)(128+120*Math.Cos(phi/360*Math.PI*2)));

      for (int i=0;i<1000;i++) {
        bmp.SetPixel(random.Next(255),random.Next(255),Color.FromArgb(255,random.Next(255),random.Next(255),random.Next(255)));
      }

      dc_client.DrawImage(bmp,128,128);
   }

   public static void Main() {
      Application.Run(new BitmapThread());
   }

   private Bitmap     bmp;
   private Graphics   dc_paint;
   private Graphics   dc_client;
   private Timer      timer;
   private SolidBrush brush;
   private float      phi;
   private Random     random;
}