gpt4 book ai didi

c# - winForm 无效(矩形)

转载 作者:太空宇宙 更新时间:2023-11-03 11:00:53 25 4
gpt4 key购买 nike

我想画飞机从左到右横穿的动画。

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。飞机是透明的

最佳答案

您可以通过为您的表单设置 DoubleBuffering 样式来解决此问题以消除闪烁,例如

DoubleBuffered = true;

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

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

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

关于c# - winForm 无效(矩形),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17772433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com