2012-09-18 94 views
1

我有一個區域在我的JPanel由點(0,0)和(寬度,高度)界定。這是一個廣場。尋找最大的字體大小,以適應區域 - Java

我有一句話

String s; 

我想找到我可以使用s最大的字體大小。現在,我知道有一種方法可以使用FontMetrics並使用for循環來繼續增加字體的大小,直到它不適合該區域。但是這樣做效率低下,必須有一種方法來計算給定字體類型的字體大小,例如適合該區域的「Courier」。壞路

例子:

Font f = new Font("Courier", Font.PLAIN, 1); 
FontMetrics fm = this.getFontMetrics(f); //this is a JPanel 
do { 
    f = new Font("Courier", Font.PLAIN, f.getSize()+1); 
    fm = this.getFontMetrics(f); 
while(fm.stringWidth(s) < width && fm.getHeight() < height); 
+0

對於非等寬字體,每個字符可以是不同的寬度。所以,你必須迭代字符串的長度,加上每個字符的相對寬度,然後乘以當前字體大小的一個因子。這聽起來就像你已經描述的方法一樣「低效」。 – DGH

+1

_「但這是低效的_」 - 你需要它的效率如何?我已經成功地在生產代碼中實現了這種方法,它每秒鐘都在繪製數百個包含文本的多邊形,並且它運行得非常順利 - 它在Java 1.4上。 – npe

+0

所以你們基本上都在說這是最好的方法嗎?我只是認爲會有更好的東西。 – CodeGuy

回答

1

我有同樣的問題,發現一個解決方案,就是一點點的優化,這一比例僅爲遍歷所有字體大小。我試圖通過調整diff文件,我要麼增加或減少對最佳字體大小收斂,直到我找到低於1

Graphics2D graphics = image.createGraphics(); 
graphics.setColor(Color.black); 

if (subtitleFont == null) { 
    //create rectangle first (from a separate library 
    int[] rect = matrix.getEnclosingRectangle(); 
    // define the maximum rect for the text 
    Rectangle2D maxRect = new Rectangle2D.Float(0, 0, w - 7, h - rect[0] - rect[3] - 10); 

    subtitleX = 0; 
    subtitleY = 0; 
    // starting with a very big font due to a high res image 
    float size = 80f * 4f; 
    // starting with a diff half the size of the font 
    float diff = size/2; 
    subtitleFont = graphics.getFont().deriveFont(Font.BOLD).deriveFont(size); 
    FontMetrics fontMetrics = graphics.getFontMetrics(subtitleFont); 
    Rectangle2D stringBounds = null; 

    while (Math.abs(diff) > 1) { 
     subtitleFont = subtitleFont.deriveFont(size); 
     graphics.setFont(subtitleFont); 
     fontMetrics = graphics.getFontMetrics(subtitleFont); 
     stringBounds = fontMetrics.getStringBounds(options.subtitle, graphics); 
     stringBounds = new Rectangle2D.Float(0f, 0f, (float) (stringBounds.getX() + stringBounds.getWidth()), (float) (stringBounds.getHeight())); 

     if (maxRect.contains(stringBounds)) { 
      if (0 < diff) { 
       diff = Math.abs(diff); 
      } else if (diff < 0) { 
       diff = Math.abs(diff)/2; 
      } 
     } else { 
      if (0 < diff) { 
       diff = - Math.abs(diff)/2; 
      } else if (diff < 0) { 
       if (size <= Math.abs(diff)) { 
        diff = - Math.abs(diff)/2; 
       } else { 
        diff = - Math.abs(diff); 
       } 
      } 
     } 
     size += diff; 
    } 

    subtitleX = (int) ((w/2) - (stringBounds.getWidth()/2)); 
    subtitleY = (int) (h - maxRect.getHeight() + fontMetrics.getAscent()); 
} 

graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, 
     RenderingHints.VALUE_TEXT_ANTIALIAS_ON); 
graphics.drawString(options.subtitle, subtitleX, subtitleY); 

我已經嘗試了DIFF字體大小與圖像的不同分辨率和的大小字體。它需要10到12次迭代,直到找到一個適合最大矩形的字體。我希望這會對某人有幫助。