Java lineTo() 非常慢

Java lineTo() is incredible slow

你好我想用java画线,刷新率为60fps:

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;

import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.util.Duration;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
import javafx.event.EventType;
import javafx.scene.paint.Color;

public class Example extends Application 
{
    public static void main(String[] args) 
    {
        launch(args);
    }

    @Override
    public void start(Stage theStage) 
    { 
        Group root = new Group();
        Scene theScene = new Scene( root );
        theStage.setScene( theScene );

        Canvas canvas = new Canvas( 512, 512 );
        root.getChildren().add( canvas );

        GraphicsContext gc = canvas.getGraphicsContext2D();           

        Timeline gameLoop = new Timeline();
        gameLoop.setCycleCount( Timeline.INDEFINITE );

        final long timeStart = System.nanoTime() -10000000000000l;

        KeyFrame kf = new KeyFrame(
            Duration.seconds(0.017),                // 60 FPS
            new EventHandler<ActionEvent>()
            {
                public void handle(ActionEvent ae)
                {                                        

                    // Clear the canvas
                    gc.clearRect(0, 0, (int)canvas.getWidth(),(int)canvas.getHeight());


                   for(int i=0;i<(int)(canvas.getWidth()/10);i++) {

                       //gc.setS
                       for(int j=0;j<10;j++)
                       {
                           if(j==0){gc.setStroke(Color.web("#000000"));}
                           else{gc.setStroke(Color.web("#aaaaaa"));}
                          gc.moveTo(j+i*10, 110);
                          gc.lineTo(j+i*10, canvas.getHeight());

                          //using gc.stroke instead of moveTo and lineTo works with good performance,but i need 1px width
                          //gc.strokeLine(j+i*10, 110, j+i*10, canvas.getHeight());
                       }

                   }
                   gc.stroke();              

                }
            });

        gameLoop.getKeyFrames().add( kf );
        gameLoop.play();

        theStage.show();

        theScene.widthProperty().addListener(observeable -> {
                    canvas.setWidth(theScene.getWidth());
                    });       

    }
}

然而,这太慢了,程序会崩溃。使用 "strokeLine()" 它运行正常,但我真的需要绘制宽度为 1px 的线条。

我想我必须在绘制完整图之前将图保存在缓冲区中 scene.But 我读到 javafx 正在保留 you.so 中的低级内容 还有另一个吗绘制 1px 线的方法?

您没有在每次迭代时将路径重置为空。因此,路径笔画正在累积:第一次迭代有 500 行,第二次有 1000 行,第三次有 1500 行,等等。

你需要

gc.beginPath();

你打电话后 gc.clearRect(...);