我试图用 javaFx 实现一个多行 TextInput,一个能够显示表情符号的文本输入,我使用了 FlowPanes 的 VBox(每行一个 FlowPane),将行按空格分割成单词,显示单词在 HBox 中,HBox 将包含用于文本的 Text 节点和用于 Emojis 的 ImageView,当前设置如下图所示
以下屏幕截图显示了我目前所拥有的
我面临的问题是复杂的词,当多个表情符号 (ImageViews) 显示在 HBox 中时,每个图像的 Carret 位置估计都会错误半个像素(因为我假设宽度为HBox 将等于其子项的 fitWidths 的总和 ?,但事实并非如此),就好像 HBox 具有某种间距,尽管间距属性设置为 0。
如果很多表情符号一起显示效果会更差,如下图所示
它也不是填充或边框,任何帮助将不胜感激,我很抱歉冗长乏味的解释,我不得不添加它,以防它可以帮助任何人帮助我解决问题。
答案 0 :(得分:3)
经过大量调查,原来是我将子ImageViews的fitWidth设置为十进制值(非整数)引起的,ImageView接受double作为fitWidth但它似乎四舍五入到最接近的渲染时更大的整数,调用 getFitWidth() 方法仍会返回您设置的双精度值,但父级将使用四舍五入的值布置它们(因为我猜物理像素不能显示半个像素对吗?)。>
因此,在 HBox 父级上调用 getWidth() 将返回比子 ImageViews 的 fitWidths 总和更大的值仅当ImageViews 的 fitWidths 为非整数时。
这可以使用以下代码进行测试
ArrayList<Image> images = new ArrayList<Image>();
//Fill the list with N images
StackPane root = new StackPane();
root.setPadding(new Insets(15));
HBox parent = new HBox(0);
for (Image image : images) {
ImageView view = new ImageView(image);
view.setPreserveRatio(true);
view.setFitWidth(fitWidth);
parent.getChildren().add(view);
}
root.getChildren().add(parent);
ps.setOnShown(event -> {
double sum = 0;
for (Node node : parent.getChildren()) {
sum += ((ImageView) node).getFitWidth();
}
System.out.println("fitWidth : " + fitWidth);
System.out.println("Sum of fitWidths of child ImageViews : " + sum);
System.out.println("Width of the parent HBox : " + parent.getWidth());
});
ps.setScene(new Scene(root));
ps.show();
以 31.5 和 32.0 的 fitWidth 运行它会得到以下结果
fitWidth : 31.5
Sum of fitWidths of child ImageViews : 315.0
Width of the parent HBox : 320.0
fitWidth : 32.0
Sum of fitWidths of child ImageViews : 320.0
Width of the parent HBox : 320.0
请注意,父级的宽度相同但 fitWidths 的总和不同,因为该值在布局或渲染过程中的某个点被四舍五入,这导致了问题中描述的问题。
解决这个问题会因上下文而异,我通过在设置 fitWidth 时将 double 转换为 int 来解决它,但这实际上取决于开发人员。