Windows窗体位图与绘图速度

时间:2017-04-08 17:38:24

标签: c# winforms graphics bitmap drawing

我在多维数组中有数据,我希望在网格中的形式上绘制它(不同的值是不同的颜色)。现在写我正在使用Panel控件并在其OnPaint()中通过为数组中的每个条目调用Graphics.DrawRectangle()来完成绘图。数据变化非常频繁,所以我在面板上调用Refresh(),但这很慢,我得到了很多闪烁,我也可以看到每个矩形的绘图按顺序发生,我知道矩形的平行绘制是不可能的,因为它不是线程安全的。

构建一个Bitmap,其中每个像素都是数组中的一个条目,然后将PictureBox设置为显示Bitmap(并缩放其大小)比使用小组和OnPaint

以下是我正在使用的代码示例:

namespace PredPreySim
    {
    public partial class SimulationForm : Form
    {
        Simulation simulation; // instance of the simulation class
        bool running = true;
        int simWidth = 30;
        int simHeight = 20;
        int cellSize = 15;

        System.Threading.Thread t;

        public SimulationForm()
        {
            InitializeComponent();
            simulation = new Simulation(simWidth, simHeight, numHerbivores, 0.3);
            graphicsTimeDelay = Convert.ToInt32(GraphicsTimeDelay.Value);
            ResizePanel();
        }

        private void ResizePanel()
        {
            panel1.Width = simWidth * cellSize;
            panel1.Height = simHeight * cellSize;
        }


        // draws the board
        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            Graphics graphics = e.Graphics;
            SolidBrush brush = new SolidBrush(Color.Green);
            RectangleF rectangle = new Rectangle();
            rectangle.Width = cellSize;
            rectangle.Height = cellSize;

            // draw all the plants
            Color plantColor;
            for (int i = 0; i < simWidth; ++i)
            {
                for (int j = 0; j < simHeight; ++j)
                {
                    int r, g = 255, b;
                    r = b = 255 - (int)(255.0 * Math.Tanh(simulation.plants[i, j]));
                    plantColor = Color.FromArgb(100, r, g, b);
                    brush.Color = plantColor;
                    rectangle.Location = new PointF(i * cellSize, j * cellSize);
                    graphics.FillRectangle(brush, rectangle);
                }
            }

            brush.Dispose();
            graphics.Dispose();
        }

        private void StartStopButton_Click(object sender, EventArgs e)
        {
            if (running) // then stop
            {
                running = false;
                StartStopButton.Text = "Start";
            }
            else // start
            {
                running = true;
                StartStopButton.Text = "Stop";
                t = new Thread(new ThreadStart(this.runSimulation));
                t.Start();
                t.Priority = System.Threading.ThreadPriority.Highest;
            }
        }

        private void runSimulation()
        {
            while (running)
            {
                simulation.Update();
                panel1.Invoke(new MethodInvoker(Refresh)); // makes the call thread-safe   
            }
            t.Abort();
        }
    }
}

0 个答案:

没有答案