好的,我对c#图形很陌生,我正在尝试制作一个自上而下的冒险游戏类型。问题是背景闪烁上方显示的任何内容。一切都是来自 png 文件的位图。背景不闪烁,所以我不知道哪里出错了。这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AITS
{
public partial class Form1 : Form
{
Background background;
Foreground foreground;
Character player;
Graphics g;
public Form1()
{
InitializeComponent();
Console.WriteLine(Environment.CurrentDirectory);
background = new Background(Properties.Resources.background, Width, Height);
foreground = new Foreground(100, Width);
player = new Character();
DoubleBuffered = true;
Paint += DrawScreen;
KeyDown += KeyPressed;
Shown += Form1_Shown;
g = CreateGraphics();
}
private void Form1_Shown(Object sender, EventArgs e)
{
gameLoop();
}
private void DrawScreen(object sender, PaintEventArgs args)
{
background.Draw(g);
player.Draw(g);
foreground.Update(Height, Width);
foreground.Draw(g);
}
private void KeyPressed(object sender, KeyEventArgs e)
{
Console.WriteLine(e.KeyData.ToString());
}
public void gameLoop()
{
while (this.Created)
{
Invalidate();
Refresh();
Application.DoEvents();
}
}
}
}
编辑:好的,我找到了答案,对于像我这样找不到这个的人:g 应该 = 参数。图形。不要使用 CreateGraphics()!
屏幕闪烁,因为窗体首先重绘其背景,然后才允许您在其上绘画。
您可以通过覆盖WndProc
来暂停此行为:
private const int WM_ERASEBKGND = 20;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_ERASEBKGND)
{
m.Result = IntPtr.Zero;
}
else
{
base.WndProc(ref m);
}
}
好的,我找到了答案,对于像我这样找不到这个的人:g 应该 = args。图形。不要使用 CreateGraphics()!