I've made some calculations to measure speed of PixelWriter, and results are not good, as I can see.
Shortly: it takes 5-10 milliseconds to renew 2 megapixel WritableImage ( with Sandy Bridge 2500 and Radeon 6850 ), and I think it is a quite slow. But maybe I've made wrong test. Please, can anybody take a look and relaunch the code?
Other examples would be cool to see!
import java.nio.IntBuffer;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.image.WritablePixelFormat;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
class BackWorker implements Runnable {
int width;
int height;
int[] data;
boolean runOk = true;
public BackWorker(int w, int h) {
width = w;
height = h;
data = new int[w * h];
(new Thread(this)).start();
}
@Override
public void run() {
Random rand = new Random();
while (runOk) {
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Logger.getLogger(BackWorker.class.getName()).log(Level.SEVERE, null, ex);
}
for (int i = 0; i < 100000; i++) {
int a = rand.nextInt(width);
int b = rand.nextInt(height);
int randomColor = rand.nextInt();
data[b * width + a] = randomColor;
}
}
}
}
public class JavaFXApplication12 extends Application {
static final int W = 1600;
static final int H = 1000;
Timeline t;
BackWorker backWorker;
int iterationNumber = 0;
@Override
public void start(Stage primaryStage) {
final WritableImage wim = new WritableImage(W, H);
backWorker = new BackWorker(W, H);
final PixelWriter pw = wim.getPixelWriter();
final WritablePixelFormat<IntBuffer> format = WritablePixelFormat.getIntArgbInstance();
t = new Timeline();
t.getKeyFrames().addAll(
new KeyFrame(Duration.ZERO),
new KeyFrame(Duration.INDEFINITE));
t.currentTimeProperty().addListener(new InvalidationListener() {
@Override
public void invalidated(Observable o) {
long timeStart = System.nanoTime();
pw.setPixels(0, 0, W, H, format, backWorker.data, 0, W);
System.out.println(System.nanoTime() - timeStart);
}
});
t.playFromStart();
ImageView iview = new ImageView(wim);
StackPane root = new StackPane();
root.getChildren().add(iview);
Scene scene = new Scene(root, W, H);
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent t) {
backWorker.runOk = false;
}
});
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}