我需要一个JavaFX程序,可以将文本设置为随机颜色和不透明度,但我不确定如何实现。
这是我的代码示例:
Text text1 = new Text();
text1.setText("Java");
text1.setFont(Font.font("Times New Roman", FontWeight.BOLD, FontPosture.ITALIC, 22));
text1.setRotate(90);
gridpane.add(text1, 3, 1);
Math.random()
生成一个位于[0,1)
范围内的Double
,所以你需要执行以下操作:
text.
setOpacity
(Math.random());
text.
setFill
(
Color.color
(Math.random(), Math.random(), Math.random());
setFill
来自于Shape
,而Text
继承自Shape
。 setFill
接受一个Paint
,而Color
是最简单的实现。 Color.color(double,double,double)
以double值的形式获取rgb值,这些double值在[0,1]范围内。Math.random()
产生的是[0,1)范围内的值。如果你不熟悉这种表示法,这意味着Math.random()
永远不会生成1,而只会生成小于1的数字。因此,使用此方法,你将永远不能得到100%完全不透明/红/绿/蓝的效果,但实际上你可能无法分辨出差异,所以最好使用更简单的方法。注意2:javafx.scene.paint.Color#color实际上提供了一个包括不透明度的四参数构造函数,但我建议像上面那样设置文本节点本身的不透明度,而不是颜色的不透明度。
像这样:
Text randomColorText(String txt) {
Text t = new Text(txt);
Random rng = new Random();
int c = rng.nextInt();
int r = c & 255;
int g = (c >>> 8) & 255;
int b = (c >>> 16) & 255;
double op = (c >>> 24) / 255.0;
t.setFill(Color.rgb(r, g, b, op));
// or use only r,g,b above and set opacity of the Text shape: t.setOpacity(op);
return t;
}
Color.color
,它有一个 rgb 选项。你需要三个随机数,因为该方法需要三个值。 - CAD97javafx.scene.paint.Color
,而不是其他的颜色类,例如java.awt
中的颜色类,因为只有 JavaFX 的颜色类在这种情况下才能正常工作。对我来说它就像现成的一样工作。 - CAD97