【问题标题】:Calculate StyledText height using text content使用文本内容计算 StyledText 高度
【发布时间】:2021-09-10 12:39:07
【问题描述】:

给定一个StyledText,用SWT.MULTISWT.WRAP 初始化,我需要根据内容的适当行数计算适当的高度提示。

在这张图片中,您可以看到编辑器在内容更改时如何调整大小

计算要显示的行的代码如下

private int calcRealLinesCount() {
  final int componentWidth = styledText.getSize().x;
  final int dumbLinesCount = styledText.getLineCount();
  int realLinesCount = 0;

  for (int i = 0; i < dumbLinesCount; i++) {
    final String lineText = styledText.getLine(i);
    final Point lineTextExtent = styledTextGc.textExtent(lineText);
    final double lines = lineTextExtent.x / (double) componentWidth;
    realLinesCount += (int) Math.max(1D, Math.ceil(lines));
  }

  return Math.max(dumbLinesCount, realLinesCount);
}

然后使用行数来获得适当的高度

((GridData) layoutData).heightHint = realLinesCount * fontHeight;

但是,此代码不考虑自动换行,我想不出办法。
有任何想法吗?我可以换一种方式吗?

【问题讨论】:

  • 为什么需要高度?我想说让 StyledText 填充所有可用空间或只是固定大小更常见。 org.eclipse.jface.text.JFaceTextUtil 有一个 computeLineHeight 声称可以处理 wrap。
  • @greg-449 不幸的是,我需要保持这种行为,否则我也会将其保持在固定大小。我会试试 computeLineHeight 并报告。谢谢!
  • @greg-449 非常感谢!你可以在我的回答中看到我的结果。

标签: java swt styledtext


【解决方案1】:

感谢 Greg 的 JFaceTextUtil#computeLineHeight 提示。
我无法直接使用它,但我至少了解了 JFace 如何满足我的需求。

以下是我现在用来获取StyledText 的行高:

private int computeRealLineHeight(final int lineIndex) {
  final int startOffset = styledText.getOffsetAtLine(lineIndex);
  final String lineText = styledText.getLine(lineIndex);

  if (lineText.isEmpty()) {
    return styledText.getLineHeight(startOffset);
  }

  final int endOffset = startOffset + lineText.length() - 1;
  final Rectangle textBounds = styledText.getTextBounds(startOffset, endOffset);
  return textBounds.height;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 2020-09-23
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多