快照图像不能用作舞台图标

时间:2016-12-08 00:47:23

标签: javafx

我正在尝试将舞台快照中的图像设置为舞台图标。

以下代码演示了它:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import java.io.IOException;

public class IconTest extends Application {

  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage primaryStage) throws Exception {
    Scene scene = new Scene(new StackPane(new ImageView(generateIcon(32))));
    primaryStage.setScene(scene);
    primaryStage.getIcons().setAll(generateIcon(32));
    primaryStage.show();
  }

  private static Image generateIcon(int dimension) throws IOException {
    Pane root = new Pane();
    root.setBackground(new Background(new BackgroundFill(Color.RED, null, null)));
    Scene scene = new Scene(root, dimension, dimension);

    return scene.snapshot(new WritableImage(dimension, dimension));
  }
}

结果:

enter image description here

如您所见,舞台图标不是红色方块。 为什么?从文件加载始终有效,使用AWT生成图像也是有效的。

解决方法:

BufferedImage bimg = new BufferedImage(dimension, dimension, BufferedImage.TYPE_INT_ARGB);
SwingFXUtils.fromFXImage(scene.snapshot(new WritableImage(dimension, dimension)), bimg);
SwingFXUtils.toFXImage(bimg, new WritableImage(dimension, dimension));

0 个答案:

没有答案