JavaFX 8 Canvas Snapshot with alpha

2020-04-07 07:02发布

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.

1条回答
趁早两清
2楼-- · 2020-04-07 07:18

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.

查看更多
登录 后发表回答