2016-10-31 45 views
0

我使用此方法測量Swing圖形中的文本邊界 但它並未覆蓋整個文本。 它在測量身高時特別不好... 當我輸入英文文本時它會變得更好,但我應該使用波斯語字體。在Swing Graphics2d中測量文本邊界

texts and bounds image

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); 
+0

你錯過了偏移。你嘗試過使用'gv.getVisualBounds'嗎?你是怎麼顯示矩形/文本的?你能否包括一段你想修改的文字? – matt

+0

@matt「你怎麼顯示矩形/文本?」我編輯了這篇文章並添加了我做到的方式......「您是否嘗試過使用gv.getVisualBounds?」 gv.getVisualBounds也會得到錯誤的高度並且存在相同的問題... –

+0

您可以添加一段文本,對於我來說,獲取可視邊界封裝了包括文字在內的文字,該文字低於基線。 – matt

回答

2

這裏有兩種方式來獲得完整的字體。我只是從互聯網上抓取了一些隨機的波斯語文本,因爲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

可見: java.awt.geom.Rectangle2D中的$浮法[X = -0.2056962,Y = -9.814648 ,W = 96.76176,H = 13.558318] 字符: java.awt.geom.Rectangle2D中的$浮法[X = 0.0,Y = -12.568359,W = 97.0,H = 15.310547]

+0

它工作正常......謝謝:) –