gpt4 book ai didi

java - 如何在 JavaFX 的场景上绘制渐变?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:10:10 24 4
gpt4 key购买 nike

有没有办法在 JavaFX 舞台的整个场景上绘制从黑色到透明的径向渐变?我想实现这样的目标: Example

最佳答案

这是一个快速答案,它使用 StackPane 作为场景根,以允许添加具有从黑色到透明的径向渐变背景的叠加层。

  • 您可以调整径向渐变颜色或半径,例如将内部颜色设为 Color.BLACK.deriveColor(0, 1, 1, 0.2),以更改效果中的高光量和强度。
  • 此类渐变也可以在 CSS 中设置,因此您可以根据需要使用 CSS 而不是 Java 代码来设置效果样式。
  • 此实现的输出会受到径向渐变 strip 的影响(不确定如何进一步改进),但根据您的容忍度,这还算可以。

shaded

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.effect.BoxBlur;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.stage.Stage;

// java 8
// click on the scene to place a shaded lens effect over the scene.
public class ShadedScene extends Application {
@Override
public void start(Stage stage) {
StackPane layout = new StackPane(
new Label("Click to shade/unshade")
);
layout.setPrefSize(400, 300);

Scene scene = new Scene(layout);
makeShadeable(scene);

stage.setScene(scene);
stage.show();
}

/**
* Applies a lens effect gradient to a scene root node.
* The effect is kind of like a flashlight shining against the wall in the dark.
*
* For the gradient to be applied, the scene's root must be defined and a Pane
* to which the effect can added and removed as a child.
*
* @param scene the scene to have the effect applied.
*/
private void makeShadeable(Scene scene) {
if (scene.getRoot() == null ||
!(scene.getRoot() instanceof Pane)) {
return;
}

Pane shade = new Pane();
RadialGradient shadePaint = new RadialGradient(
0, 0, 0.5, 0.5, 1, true, CycleMethod.NO_CYCLE,
new Stop(1, Color.BLACK),
new Stop(0, Color.TRANSPARENT)
);

shade.setBackground(
new Background(
new BackgroundFill(
shadePaint, null, new Insets(-10)
)
)
);

// blur helps reduce visible banding of the radial gradient.
shade.setEffect(new BoxBlur(5, 5, 3));

Pane root = (Pane) scene.getRoot();
scene.setOnMouseClicked(event -> {
if (root.getChildren().contains(shade)) {
root.getChildren().remove(shade);
} else {
root.getChildren().add(shade);
}
});
}

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

还有其他方法可以实现与预期效果类似的效果。例如,下面的技术直接对根 Pane 应用内部阴影和颜色调整,因此不需要额外的节点。

shaded inner shadow

private void makeShadeableByInnerShadow(Scene scene) {
InnerShadow shade = new InnerShadow();
shade.setWidth(120);
shade.setHeight(120);
shade.setInput(new ColorAdjust(0, 0, -0.3, 0));

Parent root = scene.getRoot();
scene.setOnMouseClicked(event -> {
if (root.getEffect() == null) {
root.setEffect(shade);
} else {
root.setEffect(null);
}
});
}

关于java - 如何在 JavaFX 的场景上绘制渐变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24540630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com