我试图从阵列中绘制多个动态图像,但屏幕闪烁很多。
这是我的油漆类:
public void paint (Graphics g)
{
for (int i = 0 ; i < 5 ; i++)
{
if (fire [i] == true)
{
g.drawImage (missile [i], xm [i], ym [i], null);
}
}
for (int i = 0 ; i < 20 ; i++)
{
if (enemytf [i] == true)
{
g.drawImage (enemy [i], xe [i], ye [i], null);
}
}
g.drawImage (character, xc, yc, null);
}
答案 0 :(得分:1)
为避免闪烁,您需要双缓冲。这意味着对于每个动画周期,您将绘图放入 offscreen 缓冲区,然后将该屏幕外缓冲区复制到显示屏上(关于双缓冲here的wiki文章)。
使用您的代码开始的简单(未经测试)示例:
public void paint (Graphics g)
{
Image buffer = createImage(WIDTH, HEIGHT);
Graphics ig = buffer.getGraphics();
for (int i = 0 ; i < 5 ; i++)
{
if (fire [i] == true)
{
ig.drawImage(missile [i], xm [i], ym [i], null);
}
}
for (int i = 0 ; i < 20 ; i++)
{
if (enemytf [i] == true)
{
ig.drawImage(enemy [i], xe [i], ye [i], null);
}
}
ig.drawImage(character, xc, yc, null);
g.drawImage(buffer, 0, 0, this);
}
如果您可以使用Swing,它将支持幕后双缓冲,通过以下组合:
JPanel
并覆盖paintComponent
JPanel.setDoubleBuffered(true);
。自从我使用Swing进行双重缓冲后已经有一段时间了,所以我不确定细节。对您帖子的评论表明它就像#1一样简单。