My previous sample suffered from single-buffer induced flickering. This example uses the Graphics object to draw onto a hidden Bitmap, which is then displayed in a picturebox (called "img_opt" in this example):
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace GFX
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
int dispX = 0, dispY = 0;
double angle = 0;
//TextureBrush myBrush = new TextureBrush(new Bitmap(@"C:\p\cSharpProjects\GFX\icon.gif"));
HatchBrush myBrush = new HatchBrush(HatchStyle.DiagonalBrick, Color.FromArgb(255,255,127,0), Color.FromArgb(255,200,200,0));
Bitmap buffer = new Bitmap(640, 512);
Graphics bfr;
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
Timer timer1 = new Timer();
timer1.Interval = 20;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
bfr = Graphics.FromImage(buffer);
bfr.TranslateTransform(320, 256);
}
private void timer1_Tick(object sender, EventArgs e){
//Random rndm = new Random();
//byte[] bytes = new byte[4];
//rndm.NextBytes(bytes);
double x, y;
angle += 0.01;
if(angle > Math.PI){
angle -= Math.PI * 2;
}
x = 200 * Math.Sin(angle);
y = 200 * Math.Cos(angle);
dispX = Convert.ToInt16(x);
dispY = Convert.ToInt16(y);
bfr.Clear(Color.FromArgb(255,63,127,255));
Pen blackPen = new Pen(Color.Black, 3);
Point point1 = new Point(-320, -256);
Point point2 = new Point(320, 256);
bfr.DrawLine(blackPen, point1, point2);
point1 = new Point(320, -256);
point2 = new Point(-320, 256);
bfr.DrawLine(blackPen, point1, point2);
bfr.FillEllipse(myBrush, new Rectangle(dispX-32, dispY-32, 64, 64));
this.img_opt.Image = buffer;
}
}
}
The flickering is gone, but I imagine this uses more system resources than its C++ equivalent of simply drawing the pre-rendered bitmap into the window.
I found that the built-in double-buffering settings didn't get rid of the flickering, but this works.
Hopefully C# beginners will be able to use this as the basis for their first graphics functions if they are having difficulties.