winForm无效(矩形)

时间:2013-07-21 12:38:52

标签: c# gdi+

我想在飞机从左侧穿过右侧的地方画动画。

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);                        
    } 
}

此代码有效,但平面的矩形以timer1.Interval的频率闪烁。我的问题是:我怎样才能避免这些闪烁?

p.s。:背景图像分辨率1024x768;飞机 - 160x87。飞机是透明的

1 个答案:

答案 0 :(得分:2)

您可以通过设置Form的DoubleBuffering样式来消除闪烁,例如

DoubleBuffered = true;

您可能想要设置更多控件样式以及自动双缓冲(在InitializeComponents之后)

this.SetStyle(
  ControlStyles.AllPaintingInWmPaint |
  ControlStyles.UserPaint |
  ControlStyles.DoubleBuffer,true);

有关自动和手动双缓冲的更多信息,请访问MSDN here