在pictureBox中绘制旋转线

时间:2012-10-21 11:39:24

标签: c# picturebox flicker

我想在PictureBox内绘制一条线的旋转动画。我使用pictureBox1.CreateGraphics()画线,但我听说这种方法不适合PictureBox。另外,我在PictureBox窗口上遇到了大量的闪烁,有什么建议吗?这是一段代码:

    private void OnTimedEvent(object source, PaintEventArgs e)
    {
        try
        {
            if (comport.BytesToRead > 0)
            {
                X = comport.ReadByte();
                Y = comport.ReadByte();
                Z = comport.ReadByte();
            }

            Graphics g = pictureBox1.CreateGraphics();
            Pen red = new Pen(Color.Red, 2);
            g.TranslateTransform(100, 80 - X);
            g.RotateTransform(120);
            g.DrawLine(red, new Point(100, 0 + X), new Point(100, 80 - X));
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        try
        {
            timer1.Interval = 1;
            pictureBox1.Invalidate();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

1 个答案:

答案 0 :(得分:1)

尝试在pictureBox1.Paint事件处理程序中移动绘图代码,然后调用pictureBox1.Invalidate whenewer,您需要重绘pictureBox1。这是如何绘制的真实方式。目前你正在闪烁,因为你每秒都会重绘你的pictureBox1,但那时你没有原始绘制。

        byte X;
        byte Y;
        byte Z;
        private void OnTimedEvent(object source, PaintEventArgs e)
        {
            try
            {
                if (comport.BytesToRead > 0)
                {
                    X = comport.ReadByte();
                    Y = comport.ReadByte();
                    Z = comport.ReadByte();
                }
                pictureBox1.Invalidate();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                timer1.Interval = 1;
                pictureBox1.Invalidate();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            Pen red = new Pen(Color.Red, 2);
            g.TranslateTransform(100, 80 - X);
            g.RotateTransform(120);
            g.DrawLine(red, new Point(100, 0 + X), new Point(100, 80 - X));
        }