Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX 8 Canvas Snapshot with alpha

I am currently working on a paint program (similar to Gimp and Photoshop) and in order to do that, I will need layers. I created a class called JImage which has a ArrayList<Canvas> layers and some methods.

public Image toImage(){ //Returns the final image which is all its layers combined into one canvas and snapshotted.
    Canvas c = new Canvas(width, height); //width and height are determined in the constructor
    for(int i=layers.size()-1;i>=0;i--){
        Canvas currLayer = layers.get(i);
        c.getGraphicsContext2D().drawImage(currLayer.snapshot(new SnapshotParameters(), new WritableImage(width,height)));
    }
    return c.snapshot(new SnapshotParameters(), new WritableImage(width,height));
}

My problem is that when you do canvas.snapshot(SnapshotParameters,WritableImage), the alpha layer is not included and the background is always white. This prevents me from sending it to a file without it having an ugly white background. Is there a way I can get an image out of multiple canvases with an alpha layer? I would prefer to use JavaFX for this solution so please give solutions within bounds of JavaFX.

like image 959
Jaboyc Avatar asked Nov 04 '15 20:11

Jaboyc


People also ask

What is GraphicsContext?

This class is used to issue draw calls to a Canvas using a buffer. Each call pushes the necessary parameters onto the buffer where they will be later rendered onto the image of the Canvas node by the rendering thread at the end of a pulse.

What is GraphicsContext in Java?

A graphics context is an object belonging to the class, Graphics. Instance methods are provided in this class for drawing shapes, text, and images. Any given Graphics object can draw to only one location. In this chapter, that location will always be one of Java's GUI components, such as an applet.

How do I add text to canvas JavaFX?

You can draw text using the fillText() and strokeText() methods of the GraphicsContext using the following snippets of code: void strokeText(String text, double x, double y) void strokeText(String text, double x, double y, double maxWidth) void fillText(String text, double x, double y)


1 Answers

Set the fill for your SnapshotParameters to Color.TRANSPARENT before you take a snapshot.

SnapshotParameters params = new SnapshotParameters();
params.setFill(Color.TRANSPARENT);
Image snapshot = currLayer.snapshot(params, null);

From the javadoc:

Sets the fill to the specified value. This is used to fill the entire image being rendered prior to rendering the node. A value of null indicates that the color white should be used for the fill. The default value is null.

like image 166
jewelsea Avatar answered Oct 22 '22 02:10

jewelsea