Bernice
Bernice

Reputation: 2592

How can I make an image move smoothly ?

I have a PictureBox image in a form which is moving with the mouse movement on the panel.

It's moving as I want it, however it's flickering all the time (like refreshes) and I learnt that it's a problem with forms.

I tried the following lines of code in the constructor of my form but no success:

SetStyle( ControlStyles.ResizeRedraw, true );

SetStyle( ControlStyles.UserPaint, true );

SetStyle( ControlStyles.AllPaintingInWmPaint, true );   

SetStyle( ControlStyles.OptimizedDoubleBuffer, true );    

This is the event handler for the mouse move if it helps to see all the picture. chipHolder is a panel and image is the image imported from file respectively.

private void grid_MouseMove(object sender, MouseEventArgs e)
{ 
      columnPosition = e.X;

      if (columnPosition != -1)
      {
          if (!(columnPosition < 35 || columnPosition > 610))
          {
                chipHolder.Controls.Clear();  
                PictureBox picBox = new PictureBox();
                chipHolder.Controls.Add(picBox);
                picBox.Image = image;
                picBox.Width = image.Width;
                picBox.Height = image.Height;
                picBox.Location = new Point(columnPosition - 33, 0);
                picBox.Show();
          }
      }
      chipHolder.Update();
}

Any ideas?

Upvotes: 0

Views: 9693

Answers (2)

Igor
Igor

Reputation: 15893

Do not recreate the PictureBox, just move it.

Just tried this, and image moves without any flickering:

private void button1_Click(object sender, EventArgs e)
{
    for (int iter = 0; iter < 500; iter++)
    {
        pictureBox1.Location = new Point(pictureBox1.Left + 1, pictureBox1.Top + 1);
        Application.DoEvents();
        System.Threading.Thread.Sleep(30);
    }
}

For mouse movements:

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    pictureBox1.Location = new Point(e.X, e.Y);
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    pictureBox1.Location = new Point(e.X + pictureBox1.Left, e.Y + pictureBox1.Top);
}

Upvotes: 4

Heather
Heather

Reputation: 2652

What Igor said:

private void grid_MouseMove(object sender, MouseEventArgs e)
{ 
      columnPosition = e.X;

      if (columnPosition != -1)
      {
          if (!(columnPosition < 35 || columnPosition > 610))
          {
                PictureBox picBox = chipHolder.Controls[0] // whatever your picbox id is;
                picBox.Location = new Point(columnPosition - 33, 0);
          }
      }
}

Upvotes: 0

Related Questions