我试图在java中获得字符的精确边界框。如果我执行(例如在swing组件中)以下操作是否正常:
public class MyFrame extends JFrame {
public MyFrame() {
super();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
private void computeWidth() {
String character = "A";
JLabel label = new JLabel();
Font font = label.getFont();
font = font.deriveFont(12);
// method with FontMetrics
FontMetrics fontMetrics = this.getFontMetrics(font);
Rectangle2D recWithMetrics = fontMetrics.getStringBounds(character, this.getGraphics());
System.out.println("recWithMetrics : " + recWithMetrics);
// method with GlyphVector outline
FontRenderContext ctx = new FontRenderContext(new AffineTransform(), true, true);
GlyphVector gv = font.createGlyphVector(ctx, character);
Rectangle2D recWithOutline = gv.getOutline().getBounds2D();
System.out.println("recWithOutline : " + recWithOutline);
}
public static void main(String[] args) {
MyFrame frame = new MyFrame();
frame.computeWidth();
frame.setVisible(true);
}
}
``` `recWithMetrics` 以及 `recWithOutline` 完全没有相同的值,是不是因为使用 `FontMetrics` 包括预付款?
1条答案
按热度按时间ercv8c1e1#
我发现得到那份工作更简单
Shape
然后用它。