C# 为什么我的屏幕闪烁,即使我有双缓冲?
好吧,我对c#graphics还很陌生,我正在尝试制作一款自上而下的冒险游戏。问题是背景上方显示的任何内容都会闪烁。所有内容都是来自png文件的位图。背景不会闪烁,所以我不知道哪里出了问题。 这是我的密码:C# 为什么我的屏幕闪烁,即使我有双缓冲?,c#,.net,graphics,C#,.net,Graphics,好吧,我对c#graphics还很陌生,我正在尝试制作一款自上而下的冒险游戏。问题是背景上方显示的任何内容都会闪烁。所有内容都是来自png文件的位图。背景不会闪烁,所以我不知道哪里出了问题。 这是我的密码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using Sys
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应=args.Graphics。不要使用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.Graphics。不要使用CreateGraphics() 这没什么区别。我自己画背景。