gpt4 book ai didi

Java lineTo() 非常慢

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:39:58 24 4
gpt4 key购买 nike

你好我想用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 线的方法吗?

最佳答案

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

你需要

gc.beginPath();

在调用 gc.clearRect(...); 之后

关于Java lineTo() 非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34998682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com