【发布时间】:2012-12-14 18:06:08
【问题描述】:
我目前正在使用 GDI+ 制作游戏,我知道这不是开发游戏的最佳解决方案,但由于这是一个学校项目,我别无选择。
大约每运行十次游戏,图形就会呈现在屏幕左上角的表单之外。
如果这有助于缩小问题范围,我会使用双缓冲。
渲染代码如下所示:
while (true)
{
// Create buffer if it don't exist already
if (context == null)
{
context = BufferedGraphicsManager.Current;
this.buffer = context.Allocate(CreateGraphics(), this.DisplayRectangle);
}
// Clear the screen with the forms back color
this.buffer.Graphics.Clear(this.BackColor);
// Stuff is written to the buffer here, example of drawing a game object:
this.buffer.Graphics.DrawImage(
image: SpriteSheet,
destRect: new Rectangle(
this.Position.X
this.Position.Y
this.SpriteSheetSource.Width,
this.SpriteSheetSource.Height),
srcX: this.SpriteSheetSource.X,
srcY: this.SpriteSheetSource.Y,
srcWidth: this.SpriteSheetSource.Width,
srcHeight: this.SpriteSheetSource.Height,
srcUnit: GraphicsUnit.Pixel);
// Transfer buffer to display - aka back/front buffer swapping
this.buffer.Render();
}
用截图更容易解释:
【问题讨论】:
-
是直接渲染到窗体还是控件上?
-
BufferedGraphicsManager是什么样的? -
它被直接渲染到表单,代码放在从Form基类派生的类中。
-
@Austin 我不太确定,它是 System.Drawing.dll 的一部分
-
听起来您有时会渲染到 Windows 桌面上下文 (DC)(如果您直接使用 WinAPI,则桌面的窗口句柄将为 0)。在开始游戏循环之前,您是否正在等待创建表单?不确定为什么要在游戏绘制循环中创建上下文/缓冲区。有什么理由可以在创建后的任何时间为空? this.buffer.Render();在这个调用中会发生什么?