**
C#双缓冲绘图
**
C#编程中,常常需要绘制图,为了提高绘制效率,避免闪烁,引入双缓冲绘图技术。废话不说,直接上代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
float phase;
float speed;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
speed = 0f;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
BufferedGraphicsContext currentContext = BufferedGraphicsManager.Current;
BufferedGraphics myBuffer = currentContext.Allocate(e.Graphics, e.ClipRectangle);
Graphics g = myBuffer.Graphics;
g.Clear(this.BackColor);
Pen blackpen = new Pen(Color.Red);
for (float i = 0; i < 700; i++)
{
g.DrawLine(new Pen(Color.Red), i, (float)(Math.Sin(i / 700 * 6 * 3.14159 + phase) * 200 + 300), i + 1, (float)(Math.Sin((i + 1) / 700 * 6 * 3.14159 + phase) * 200 + 300));
g.DrawLine(new Pen(Color.Green), i, (float)(Math.Sin(i / 700 * 6 * 3.14159 + phase + 2 * 3.14 / 3) * 200 + 300), i + 1, (float)(Math.Sin((i + 1) / 700 * 6 * 3.14159 + phase + 2 * 3.14 / 3) * 200 + 300));
g.DrawLine(new Pen(Color.Blue), i, (float)(Math.Sin(i / 700 * 6 * 3.14159 + phase + 4 * 3.14 / 3) * 200 + 300), i + 1, (float)(Math.Sin((i + 1) / 700 * 6 * 3.14159 + phase + 4 * 3.14 / 3) * 200 + 300));
}
myBuffer.Render(e.Graphics);
myBuffer.Dispose();
g.Dispose();
}
private void timer1_Tick(object sender, EventArgs e)
{
phase += speed;
if (phase > 314) phase = 0;
this.Refresh();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text != "")
speed = float.Parse(textBox1.Text);
speed = (float)(((int)(speed*100)) % 628)/100f;
}
}
}