欢迎使用优快云-markdown编辑器

本文介绍了一种使用C#实现的双缓冲绘图技术,该技术能够有效提高绘图效率并减少屏幕闪烁现象。通过具体的代码实例展示了如何设置双缓冲,并在窗口中绘制动态的彩色正弦波。

**

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;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值