gpt4 book ai didi

java - 使用 LineBreakMeasurer 计算行并更改字体大小

转载 作者:行者123 更新时间:2023-11-30 07:17:57 25 4
gpt4 key购买 nike

我已经使用其他出色的答案来设计一种返回 JTextPane 的正确尺寸的方法,给定它的内容和宽度,使用 LineBreakMeasurer

问题是当我尝试不同的字体大小时它有点不正常,我不明白为什么。它非常适合 Arial 12,但不适用于 Arial 8 或 Arial 16,因为 nextLayout 计算的长度错误。谁能告诉我为什么?

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextLayout;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.border.LineBorder;


public class Example1 {

static JFrame frame = new JFrame();
static JPanel bigPanel = new JPanel();
static JTextPane textPane[] = new JTextPane[10];



public static void main(String[] args) {

frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

for(int i=0 ; i<10 ; i++) {
textPane[i] = new JTextPane();
textPane[i].setFont(new Font("Arial", 0, 12+i ));
textPane[i].setText("This is 10 characters of " + ((Integer)(10+i)).toString() + " points : a b c d e f g h i j");
textPane[i].setPreferredSize(getTextDimension(textPane[i], 100));
textPane[i].setBorder(new LineBorder(Color.BLACK));
frame.add(textPane[i]);
}

frame.setSize(500, 500);
frame.setVisible(true);

}

static private Dimension getTextDimension(JTextPane textPane, float width) {

FontMetrics fm = textPane.getFontMetrics(textPane.getFont());
int fontHeight = fm.getHeight()+ fm.getDescent();
//int fontHeight = fm.getHeight();

AttributedString text = new AttributedString(textPane.getText());
FontRenderContext frc = textPane.getFontMetrics(textPane.getFont()).getFontRenderContext();
AttributedCharacterIterator styledText = text.getIterator();
LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

float wrappingWidth = width - textPane.getInsets().left - textPane.getInsets().right;

int lines = 0;
while (measurer.getPosition() < styledText.getEndIndex()) {
TextLayout layout = measurer.nextLayout(wrappingWidth);
lines++;
}

return new Dimension((int)Math.round(width), lines * fontHeight);
}

最佳答案

我通过在 AttributedString 实例化之后添加以下行来解决字体大小问题:

AttributedString text = new AttributedString(textPane.getText());
text.addAttribute(TextAttribute.FONT, textPane.getFont());

我猜 Attributed String 需要定义字体,虽然我认为它是由 FontRenderContext 处理的,但至少对我来说,它不是。

关于java - 使用 LineBreakMeasurer 计算行并更改字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15712972/

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