I have two balls (ellipses) in a List of balls which are drawn on a PictureBox.
The balls should be moving around, i.e. I change the position and then call Refresh().
The result is that only the second ball is shown. The first is never shown.
I have searched for a solution but not been able to find anything which helps.
With one ball everything works fine. But the Refresh() seems to "delete" the first ball and only "keeps" the second one.
I would be thankful if anyone could point me in the right direction here (have been searching but not found anything useful).
Thanks
Added some information about the code:
List of balls:
private List<Ball> balls = new List<Ball>();
After adding the balls to a list I call the paint method with
foreach(Ball b in balls)
{
b.paintBall(e, pictureBox1);
}
The paint method:
public void paintBall(PaintEventArgs e, PictureBox myPictureBox)
{
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.Clear(myPictureBox.BackColor);
e.Graphics.FillEllipse(farbe, ballPosX, ballPosY, ballWidth, ballHeight);
e.Graphics.DrawEllipse(Pens.Black, ballPosX, ballPosY, ballWidth, ballWidth);
}
fyi - "farbe" is declared as Brush (to be able to set a color).
Then updating the position (by using a timer), calling the move-Method, after which I have the Refresh() method
foreach (Ball b in balls)
{
b.moveBall(pictureBox1);
}
pictureBox1.Refresh();
The moveBall method:
public void moveBall(PictureBox pictureBox)
{
ballPosX += moveStepX;
if (ballPosX < 0 || (ballPosX + ballWidth > pictureBox.ClientSize.Width))
moveStepX = -moveStepX;
ballPosY += moveStepY;
if (ballPosY < 0 || (ballPosY + ballHeigth > pictureBox.ClientSize.Height))
moveStepY = -moveStepY;
}

You are calling
e.Graphics.Clear(myPictureBox.BackColor);for each ball. Therefore, the previous ones will be deleted.Instead paint balls like this:
And do this in the
pictureBox1Paintevent handler. Do not call paint methods directly.pictureBox1.Refresh();will do that for you. The advantage in doing so is thatpictureBox1_Paintwill be called automatically when necessary. E.g., when a window is minimized and then restored or when a window is being resized, etc.You can also extract the ball painting in another method and then do:
It is even easier if you add a Paint method to the
Ballclass itself:In
pictureBox1_Paintyou can write:There are advantages in doing so:
X,Yetc.Shapehaving all the common properties and an abstractPaintmethod. Derived classes likeBallorSquarewould then overridePaintand provide their own implementation. Instead of having aList<Ball>you would have aList<Shape>.