Evitando criar PictureBoxes repetidamente
Eu tenho o seguinte problema. Minha intenção é mover várias imagens da direita para a esquerda em um Windows Form. O código abaixo funciona muito bem. O que me incomoda é o fato de que toda vez que um objeto PictureBox é criado, esse procedimento consome enormes quantidades de memória. Cada imagem segue a imagem anterior ininterruptamente da direita para a esquerda. As imagens mostram um céu se movendo de um lado para outro. Deve parecer um avião voando pelo ar.
Como é possível evitar o uso de muita memória? Existe algo que eu possa fazer com o PaintEvent e o GDI? Não estou muito familiarizado com programação gráfica.
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
public class Background : Form
{
private PictureBox sky, skyMove;
private Timer moveSky;
private int positionX = 0, positionY = 0, width, height;
private List<PictureBox> consecutivePictures;
public Background(int width, int height)
{
this.width = width;
this.height = height;
// Creating Windows Form
this.Text = "THE FLIGHTER";
this.Size = new Size(width, height);
this.StartPosition = FormStartPosition.CenterScreen;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
// The movement of the sky becomes possible by the timer.
moveSky = new Timer();
moveSky.Tick += new EventHandler(moveSky_XDirection_Tick);
moveSky.Interval = 10;
moveSky.Start();
consecutivePictures = new List<PictureBox>();
skyInTheWindow();
this.ShowDialog();
}
// sky's direction of movement
private void moveSky_XDirection_Tick(object sender, EventArgs e)
{
for (int i = 0; i < 100; i++)
{
skyMove = consecutivePictures[i];
skyMove.Location = new Point(skyMove.Location.X - 6, skyMove.Location.Y);
}
}
private void skyInTheWindow()
{
for (int i = 0; i < 100; i++)
{
// Loading sky into the window
sky = new PictureBox();
sky.Image = new Bitmap("C:/MyPath/Sky.jpg");
sky.SetBounds(positionX, positionY, width, height);
this.Controls.Add(sky);
consecutivePictures.Add(sky);
positionX += width;
}
}
}