我需要获取上面的图片和文字。我创建了StackPane并将ImageView和Group中的Text元素放在里面。我想调整StackPane的大小,并将ImageView比例和文本组的位置保持在此ImageView上。下面的代码有效,但是当我调整StackPane的大小时,我无法修复文本组的位置。
小窗口。图像顶部的文字顶部
大窗口。低于图像顶部的文本顶部
public class SlideFromText extends Slide {
private StackPane sp = new StackPane();
private ImageView iv = new ImageView();
private Group text_group = new Group();
public SlideFromText(Image img, String text_string) {
iv.setImage(img);
iv.setPreserveRatio(true);
iv.fitWidthProperty().bind(sp.widthProperty());
iv.fitHeightProperty().bind(sp.heightProperty());
sp.setAlignment(Pos.TOP_CENTER);
sp.setMinSize(0, 0);
sp.getChildren().add(iv);
String lines[] = text_string.split("\\r?\\n");
double height = 0;
double maxWidth = 0;
String font_name = (String) Options.getOption("font");
Font f = new Font(font_name, 20);
ArrayList<Text> text_array = new ArrayList<>();
for (String line : lines) {
Text text = new Text(line);
text.setFont(f);
text.setFill(Color.WHITE);
text.setTextOrigin(VPos.BASELINE);
text.setTextAlignment(TextAlignment.CENTER);
DropShadow sh = new DropShadow(3, Color.BLACK);
sh.setSpread(0.25);
text.setEffect(sh);
height += text.getBoundsInParent().getHeight();
text.setY(height);
text.setX(sh.getRadius() / 2);
maxWidth = Math.max(maxWidth, text.getBoundsInParent().getWidth());
text_array.add(text);
}
for (Text t : text_array) {
t.setWrappingWidth(maxWidth);
}
text_group.getChildren().addAll(text_array);
sp.getChildren().add(text_group);
iv.boundsInParentProperty().addListener(new ChangeListener<Bounds>() {
@Override
public void changed(ObservableValue<? extends Bounds> observable, Bounds oldValue, Bounds newValue) {
Node node = sp.getChildren().get(1);
if (node.getClass() != Group.class) {
return;
}
Group group_node = (Group) node;
group_node.setLayoutX(-1.0 * group_node.layoutBoundsProperty().get().getWidth() / 2.0);
group_node.getTransforms().clear();
double scale_x = (iv.getBoundsInParent().getWidth() * 0.95) / group_node.getBoundsInParent().getWidth();
double scale_y = (iv.getBoundsInParent().getHeight() * 0.95) / group_node.getBoundsInParent().getHeight();
double scale_factor = Math.min(scale_x, scale_y);
double pivot_x = (group_node.getBoundsInLocal().getMaxX() - group_node.getBoundsInLocal().getMinX()) / 2;
Scale scale = new Scale(scale_factor, scale_factor, pivot_x, 0);
group_node.getTransforms().add(scale);
}
});
}
@Override
public Pane getPane() {
return sp;
}
}