我试图用Canvas创建一个粒子系统。有趣的是,drawImage方法非常快。即使使用drawImage,我也能以60 fps达到90.000个粒子。但是,那只是相同的图像。当我为粒子使用不同的图像时,性能显着下降。然后我改变了图像的顺序,这样e。 G。首先绘制image1的所有粒子,然后绘制所有image2等,并且性能再次良好。
问题
有谁知道这是为什么?人们必须考虑drawImage中是否有一些内部缓存机制?
代码
这里的示例代码:
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class CanvasExample extends Application {
GraphicsContext gc;
double width = 800;
double height = 600;
Image[] images;
@Override
public void start(Stage primaryStage) {
Canvas canvas = new Canvas(width, height);
gc = canvas.getGraphicsContext2D();
BorderPane root = new BorderPane();
root.setCenter(canvas);
Scene scene = new Scene(root, width, height);
scene.setFill(Color.BEIGE);
primaryStage.setScene(scene);
primaryStage.show();
createImages(255);
AnimationTimer loop = new AnimationTimer() {
double prev = 0;
double frameCount = 0;
double fps = 0;
@Override
public void handle(long now) {
// very basic frame counter
if(now - prev > 1_000_000_000) {
System.out.println("FPS: " + frameCount);
fps = frameCount;
prev = now;
frameCount = 0;
} else {
frameCount++;
}
// clear canvas
gc.setFill(Color.BLACK);
gc.fillRect(0, 0, width, height);
// paint images
int numIterations = 90000;
for(int i=0; i < numIterations; i++) {
int index = i % 2; // <==== change here: i % 1 is fast, i % 2 is slow
gc.drawImage(images[ index], 100, 100);
}
gc.setFill(Color.WHITE);
gc.fillText("fps: " + fps, 0, 10);
}
};
loop.start();
}
public void createImages(int count) {
Rectangle rect = new Rectangle(10,10);
rect.setFill(Color.RED);
images = new Image[count];
for(int i=0; i < count; i++) {
images[i] = createImage(rect);
}
}
/**
* Snapshot an image out of a node, consider transparency.
*
* @param node
* @return
*/
public Image createImage(Node node) {
WritableImage wi;
SnapshotParameters parameters = new SnapshotParameters();
parameters.setFill(Color.TRANSPARENT);
int imageWidth = (int) node.getBoundsInLocal().getWidth();
int imageHeight = (int) node.getBoundsInLocal().getHeight();
wi = new WritableImage(imageWidth, imageHeight);
node.snapshot(parameters, wi);
return wi;
}
public static void main(String[] args) {
launch(args);
}
}
这是非常基本的。图像是从一个矩形创建的,然后放入一个数组中,并在AnimationTimer循环中,图像在画布上绘制numIterations-times。
当您使用index = i % 1
,我。即一遍又一遍的相同图像,然后在我的系统上的fps是60帧/秒。如果您使用index = i % 2
,我。即交替的图像,那么我的系统上的fps是14 fps。这是相当大的差异。
非常感谢您的帮助!