Java lineTo()非常慢

时间:2016-01-25 17:34:09

标签: java performance javafx drawing

您好我想用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的线宽。

我想在绘制完整场景之前我必须将图形保存在缓冲区中。但是我读到javafx正在保留你的低级内容。那么还有另一种绘制1px线的方法吗?

1 个答案:

答案 0 :(得分:3)

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

你需要

gc.beginPath();

致电gc.clearRect(...);