首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >winForm无效(矩形)

winForm无效(矩形)
EN

Stack Overflow用户
提问于 2013-07-21 20:38:52
回答 1查看 971关注 0票数 2

我想画飞机从左边到右边交叉的动画。

代码语言:javascript
运行
复制
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的频率闪烁。我的问题是:我如何避免这些闪烁?

附注:背景图像分辨率1024x768;平面- 160x87。平面是透明的

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-21 20:53:51

可以通过设置窗体的DoubleBuffering样式来消除闪烁来解决此问题,例如

代码语言:javascript
运行
复制
DoubleBuffered = true;

您可能还想为自动双缓冲(在InitializeComponents之后)设置更多的控件样式

代码语言:javascript
运行
复制
this.SetStyle(
  ControlStyles.AllPaintingInWmPaint |
  ControlStyles.UserPaint |
  ControlStyles.DoubleBuffer,true);

有关自动和手动双缓冲的详细信息,请参阅MSDN here

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17772433

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档