我正在尝试将一些 Java2D 代码转换为 JavaFX,但我遇到了有关 JavaFX Canvas 性能的问题。在某些时候,我将不得不在屏幕上绘制数千个小圆圈。
我的问题是在第一次绘图中,我的代码需要很多时间来执行。但是如果我必须执行第二次绘图,则只需要一小部分时间来绘制(至少快 10 倍)。
有什么我做错了吗?有什么办法可以防止最初的延迟?
我写了这段代码来测试它。在此代码中,我在 1000 x 1000 Canvas (以前构建)上的随机位置绘制了 500,000 个圆圈。我将此代码链接到按钮单击事件,第一次单击时需要 10 秒才能执行。但如果我再点击一次,只需要 0.025 秒。
private void paintCanvas() {
long initTime = System.currentTimeMillis();
GraphicsContext cg = canvas.getGraphicsContext2D();
cg.setFill(Color.WHITE);
cg.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
cg.setFill(Color.rgb(0, 0, 0, 0.1));
Random rand = new Random();
for (int i = 0; i < 500000; i++) {
cg.fillOval(1000 * rand.nextFloat(), 1000 * rand.nextFloat(), 2, 2);
}
long endTime = System.currentTimeMillis();
System.out.println("Time spent on drawing:" + (endTime - initTime)/1000.0f);
}
实际上没有最大数量的新元素。它可以从数百到数十万不等,具体取决于用户的需求。是的,如果一些元素随着时间的推移突然出现也没关系。
最佳答案
伙计们,我感谢你们的帮助。我向 OpenJFX 邮件列表发送了相同的问题,其中一位开发人员回答了。似乎我的 JavaFX 2.2 版本仍然使用旧模型来增加命令缓冲区。新版本 JavaFX 8 使用更高效的模型,使第一次绘制与后续绘制一样快。
这是我得到的答案:
Jim Graham (james.graham at oracle.com)
Mon May 12 21:17:19 UTC 2014
This is likely due to growing the command buffer which was done linearly at one point (probably still done that way in 2.2), but is now exponential in 8.0. The first render time is nearly instantaneous in 8.0, but takes a long time as you found when I try it with one of my old 2.x builds...
...jim
关于performance - JavaFX Canvas 延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23518768/