BackgroundSizeのcovertをfalseにcontainをtrueにしてみてはいかがでしょうか?
追記:質問者さんの本来の期待(処理をごりごり書くのではなく、制約として記述すること?)はCSSあるいはCSS相当のBackgroundによる指定だと思うのですが、自分には指定方法がわかりません。
回避策として多少処理を書くのであれば次のようには書けると思います。背景画像ではなくStackPaneの一番底にImageViewを配置する方法です。ImageViewならfitWidth, fitHeight, viewportの各プロパティーを制御することで比較的自由度の高い配置がプログラミングできるかと思います。
java
1public class FxImageTest extends Application {
2 @Override
3 public void start(Stage stage) throws Exception {
4 Image img = new Image(FxImageTest.class.getResource("image2.jpg")
5 .toURI().toURL().toString());
6
7 StackPane root = new StackPane();
8
9 ImageView iv = new ImageView();
10 iv.fitWidthProperty().bind(root.widthProperty());
11 iv.fitHeightProperty().bind(root.heightProperty());
12 Binding<Rectangle2D> viewport = Bindings.createObjectBinding(
13 () -> {
14 Image image = iv.getImage();
15 if (image == null) return null;
16 double vpWidth = Math.max(1, image.getWidth());
17 double vpHeight = Math.max(1, image.getHeight());
18 double imageRatio = vpWidth / vpHeight;
19 Bounds bounds = root.getBoundsInLocal();
20 double boundsRatio = Math.max(1, bounds.getWidth())
21 / Math.max(1, bounds.getHeight());
22 if (boundsRatio > imageRatio) {
23 // 元画像の上下をカット
24 vpHeight = vpWidth / boundsRatio;
25 } else {
26 // 元画像の左右をカット
27 vpWidth = vpHeight * boundsRatio;
28 }
29 return new Rectangle2D(
30 (image.getWidth() - vpWidth) * 0.5,
31 (image.getHeight() - vpHeight) * 0.5,
32 vpWidth, vpHeight);
33 },
34 root.boundsInLocalProperty(), iv.imageProperty());
35 iv.setImage(img); // viewportの初期値を設定するため。
36
37 viewport.addListener((ob, ov, nv) -> iv.setViewport(nv)); // ※補足参照
38
39 Button button = new Button("toggle background");
40 button.setOnAction(ev -> iv.setImage(iv.getImage() == null ? img : null));
41 button.setPrefSize(150, 30);
42
43 root.getChildren().addAll(iv, button);
44
45 Scene scene = new Scene(root, 800, 500);
46
47 stage.setScene(scene);
48 stage.show();
49 }
50}
※補足:
コード中の※の行ですが、本当は
iv.viewportProperty().bind(viewport);
と書きたいところですが、そうやってしまうとstack overflowが起きます。
JavaFXのプロパティーのバインドはObserverパターンを非常に簡単に利用できる点はよいのですが、ジオメトリー(ノードのレイアウト)にかかわるプロパティーに下手に依存関係を定義してしまうと内部のレイアウト処理の実装からの影響で、依存関係の循環が発生してしまう点に注意が必要です。
本件ではChangeListener経由でviewportプロパティーの設定をすることで一応回避できているように見えますが、ChangeListenerは万能ではなく、プロパティーの依存関係に本質的に巡回関係ができてしまうとどうやってもNGになる場合もあります。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/03/15 06:25
2018/03/15 06:52
2018/03/15 06:58
2018/03/15 07:30 編集
2018/03/15 07:34
2018/03/17 06:09
2018/03/17 06:15
2018/03/19 03:57