我正在使用这种方法测量Swing图形中的文本边界,但它并不涵盖整个文本。在测量高度时效果不好.当我输入英语文本时,它会变得更好,但我应该使用波斯语字体。
private Rectangle getStringBounds(Graphics2D g2, String str,
float x, float y)
{
FontRenderContext frc = g2.getFontRenderContext();
GlyphVector gv = g2.getFont().createGlyphVector(frc, str);
return gv.getPixelBounds(null, x, y);
}我就是这样画文字和界限的:
g.drawString(text, x-textBounds.width/2, y+textBounds.height/2);
g.drawRect(x-textBounds.width/2, y-textBounds.height/2, textBounds.width, textBounds.height);发布于 2016-10-31 08:59:47
以下是获得完整字体的两种方法。我只是从网上抓起了一些随意的波斯语短信,因为OP不想粘贴一个小例子。
public class BoxInFont {
String text = "سادگی، قابلیت تبدیل";
int ox = 50;
int oy = 50;
void buildGui(){
JFrame frame = new JFrame("Boxed In Fonts");
JPanel panel = new JPanel(){
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g.drawString(text, ox, oy);
Font f = g.getFont();
Rectangle2D charBounds = f.getStringBounds(text, g2d.getFontRenderContext());
GlyphVector gv = f.layoutGlyphVector(g2d.getFontRenderContext(), text.toCharArray(), 0, text.length(), GlyphVector.FLAG_MASK);
Rectangle2D bounds = gv.getVisualBounds();
g2d.translate(ox, oy);
//g2d.drawRect((int)bounds.getX() + ox, (int)bounds.getY() + oy, (int)bounds.getWidth(), (int)bounds.getHeight());
g2d.draw(bounds);
g2d.draw(charBounds);
System.out.println("vis: " + bounds);
System.out.println("char: " + charBounds);
}
};
frame.add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args){
EventQueue.invokeLater(()->new BoxInFont().buildGui());
}
}绘制的两个框都完全封装了文本。我认为视觉界更贴切。
OP的问题是,它们忽略了返回的矩形的x和y值。他们只使用宽度和高度。如果你看一下这个程序的输出,你会发现x和y不是0。
w=96.76176,h=13.558318 char: java.awt.geom.Rectangle2D$Floatx=0.0,y=-12.568359,w=97.0,h=15.310547
https://stackoverflow.com/questions/40338369
复制相似问题