Issue
How can I use Skija for JavaFX?
This is the code example from the repository
Surface surface = Surface.makeRasterN32Premul(100, 100);
Canvas canvas = surface.getCanvas();
Paint paint = new Paint();
paint.setColor(0xFFFF0000);
canvas.drawCircle(50, 50, 30, paint);
But how to convert this skija canvas object to a JavaFX node?
Solution
This answer based on James_D comment to use byte[]
as an input stream. Here is sample code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.jetbrains.skija.*;
import java.io.ByteArrayInputStream;
public class SkijaFX extends Application{
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception{
Surface surface = Surface.makeRasterN32Premul(100, 100);
Canvas canvas = surface.getCanvas();
Paint paint = new Paint();
canvas.drawCircle(50, 50, 30, paint);
Image image = surface.makeImageSnapshot();
Data data = image.encodeToData(EncodedImageFormat.PNG);
byte[] pngBytes = data.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(pngBytes);
javafx.scene.image.Image imageFx = new javafx.scene.image.Image(inputStream);
ImageView imageView = new ImageView(imageFx);
StackPane root = new StackPane(imageView);
Scene scene = new Scene(root, 300, 300);
primaryStage.setScene(scene);
primaryStage.show();
}
}
UPDATE:
As mipa suggested, if we use JavaFX 13 and above, instead of using ByteArrayInputStream
, we can use WritableImage
and PixelBuffer
to create an ImageView
Answered By - NM Naufaldo
Answer Checked By - Pedro (JavaFixing Volunteer)