带有alpha的JavaFX 8 Canvas Snapshot

时间:2015-11-04 20:23:07

标签: java canvas javafx

我目前正在制作一个绘画程序(类似于Gimp和Photoshop),为了做到这一点,我需要图层。我创建了一个名为JImage的类,它有一个ArrayList<Canvas> layers和一些方法。

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));
}

我的问题是当你canvas.snapshot(SnapshotParameters,WritableImage)时,不包括alpha图层,背景总是白色。这可以防止我在没有丑陋的白色背景的情况下将其发送到文件。有没有办法可以从多个带有alpha图层的画布中获取图像?我更愿意将JavaFX用于此解决方案,因此请在JavaFX的范围内提供解决方案。

1 个答案:

答案 0 :(得分:7)

在拍摄快照之前,

Set the fill将您的SnapshotParameters设为Color.TRANSPARENT

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

来自javadoc:

  

将填充设置为指定值。这用于在渲染节点之前填充正在渲染的整个图像。值null表示应将白色用于填充。默认值为null。