W mojej prościutkiej aplikacji, rysującej losowe prostokątyw losowych miejscach, przy każdym wywołaniu metody Invalidate(), kasowana jest poprzednia zawartość formy. Czy można zrobić coś, aby poprzednio narysowane prostokąty, nie były niszczone? Oto kod:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
namespace Ocena_gier
{
public partial class myForm : Form
{
public bool Zatrzymany = false;
public myForm()
{
InitializeComponent();
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
Invalidate();
}
private void RysujProstokat(Graphics g)
{
Random rand = new Random();
int x = rand.Next(ClientSize.Width);
int y = rand.Next(ClientSize.Height);
int sz = rand.Next(100);
int w = rand.Next(100);
Color kolor1 = Color.FromArgb(rand.Next(255), rand.Next(255), rand.Next(255));
Color kolor2 = Color.FromArgb(rand.Next(255), rand.Next(255), rand.Next(255));
if (w < 1)
w = 10;
if (sz < 1)
sz = 10;
Rectangle rect = new Rectangle(x, y, sz, w);
Brush b = new LinearGradientBrush(rect, kolor1, kolor2, LinearGradientMode.Horizontal);
g.FillRectangle(b, rect);
b.Dispose();
}
private void myForm_Paint(object sender, PaintEventArgs e)
{
Graphics g = CreateGraphics();
RysujProstokat(g);
g.Dispose();
}
private void myForm_KeyPress(object sender, KeyPressEventArgs e)
{
if ((Keys)e.KeyChar == Keys.Space)
Zatrzymany = !Zatrzymany;
if (Zatrzymany)
timer1.Stop();
else
timer1.Start();
}
}
}