2

飛行機が左から右に横切るアニメーションを描きたいです。

public partial class Form1 : Form
{
    Bitmap sky, plane, background;        
    int currentX, currentY; 
    Random rndHeight;
    Rectangle planeRect;       
    Graphics g;

    public Form1()
    {
        InitializeComponent();                 
    }

    private void Form1_Load(object sender, EventArgs e)
    {            
        try
        {
            sky = new Bitmap("sky.jpg");
            plane = new Bitmap("plane1.png");

            int planeWidth = plane.Width; int planeHeight = plane.Height;                  
        }
        catch (Exception) { MessageBox.Show("No files!"); }

        this.ClientSize = new System.Drawing.Size(sky.Width, sky.Height);            
        this.FormBorderStyle = FormBorderStyle.FixedSingle;            

        background = new Bitmap(sky);
        g = Graphics.FromImage(background);

        rndHeight = new Random();
        currentX = -plane.Width; currentY = rndHeight.Next(0, this.Height);

        this.BackgroundImage = background;

        timer1.Interval = 1;
        timer1.Enabled = true;
        timer1.Start();            
    }

    protected override void OnPaint(PaintEventArgs e)
    {            
        e.Graphics.DrawImage(sky, 0, 0);
        e.Graphics.DrawImage(plane, planeRect);            
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        g.DrawImage(sky, 0, 0);
        planeRect.X = currentX; planeRect.Y = currentY; planeRect.Width = plane.Width; planeRect.Height = plane.Height;
        g.DrawImage(plane, planeRect);
        Rectangle myNewPlane = new Rectangle(planeRect.X - 10, planeRect.Y - 10, planeRect.Width + 20, planeRect.Height + 20);
        this.Invalidate(myNewPlane); 
        if (currentX >= this.Width) currentX = -plane.Width; else currentX += 2;
        currentY += rndHeight.Next(-2, 2);                        
    } 
}

このコードは機能しますが、平面の Rectangle は timer1.Interval の頻度でちらつきます。私の質問は、これらのちらつきをどのように回避できますか?

ps: 背景画像の解像度 1024x768; 飛行機 - 160x87。平面は透明です

4

1 に答える 1