Vermeiden, immer wieder PictureBoxes zu erstellen
Ich habe folgendes Problem. Ich beabsichtige, in einem Windows Form mehrere Bilder von rechts nach links zu verschieben. Der folgende Code funktioniert ganz gut. Was mich stört, ist die Tatsache, dass jedes Mal, wenn ein PictureBox-Objekt erstellt wird, diese Prozedur enorm viel Speicher verbraucht. Jedes Bild folgt von rechts nach links ununterbrochen dem vorherigen Bild. Die Bilder zeigen einen Himmel, der sich von einer Seite zur anderen bewegt. Es sollte so aussehen, als würde ein Flugzeug durch die Luft fliegen.
Wie kann die Verwendung von zu viel Speicher vermieden werden? Kann ich mit PaintEvent und GDI etwas anfangen? Ich bin nicht sehr vertraut mit Grafikprogrammierung.
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;
}
}
}