在Java中获得真正的字符串高度,可以使用以下方法:
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class StringHeight extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
FontMetrics fm = g2d.getFontMetrics();
String text = "Hello, World!";
int stringHeight = fm.getHeight();
System.out.println("String height: " + stringHeight);
}
public static void main(String[] args) {
JFrame frame = new JFrame("String Height");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new StringHeight());
frame.setSize(300, 200);
frame.setVisible(true);
}
}
import java.awt.Font;
import java.awt.font.TextLayout;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
public class StringHeight {
public static void main(String[] args) {
String text = "Hello, World!";
Font font = new Font("Arial", Font.PLAIN, 12);
AttributedString attributedString = new AttributedString(text);
attributedString.addAttribute(TextAttribute.FONT, font);
AttributedCharacterIterator iterator = attributedString.getIterator();
TextLayout layout = new TextLayout(iterator);
float stringHeight = layout.getAscent() + layout.getDescent() + layout.getLeading();
System.out.println("String height: " + stringHeight);
}
}
这两种方法都可以获得字符串的真实高度,可以根据实际需求选择使用。
Elastic 实战工作坊
Elastic 实战工作坊
云+社区技术沙龙[第6期]
GAME-TECH
腾讯技术创作特训营第二季第3期
Elastic 实战工作坊
数字化产业研学汇第三期
领取专属 10元无门槛券
手把手带您无忧上云