2010-08-11 44 views
1

我需要文字来填充预定义区域。我不一定希望字体的增长超出一定的限制,但我宁愿它至少缩小,如果它不适合某个地区。 (所以有一个字体大小的上限,也是一个下限,但采取上限作为默认和缩小需要时。)有没有简单的方法来调整一段文字的字体大小以适合某个区域?

是否有任何简单的方法可以轻松完成这样的事情?

+1

什么是您使用的UI技术? Swing,SWT,输出到HTML ... – 2010-08-11 13:07:24

+0

您是指将出现在类似JLabel或JTextArea的组件或使用drawString()在paint()期间直接呈现的文本中的文本。会不会有包装? – 2010-08-11 13:13:07

+0

答案真的取决于您使用的UI技术。它是摇摆吗? – BalusC 2010-08-11 13:30:00

回答

1

我最终结束了使用上的PdfSignatureAppearance操作fitText,包括在iText。这使得它很容易完成。它可能不完美,但它比没有任何东西要好得多。

public static final float calculateFontSize(String fontName, float maxFontsize, float width, float height, String text) { 
    Font font = FontFactory.getFont(fontName); 
    Rectangle rectangle = new Rectangle(width, height); 
    System.err.println("Calculating font size for " + width + " and " + height); 
    return PdfSignatureAppearance.fitText(font, text, rectangle, maxFontsize, PdfWriter.RUN_DIRECTION_LTR); 
} 
0

我会选择你想使用的字体大小,以确保它们在目标输出上看起来不错。没有理由坚持3,尽可能多地使用你想要的。 )通入的getFont(矩形必须具有x上的Y都设置为0。

public class FontFactory { 
    private Font[] fonts; 

    public FontFactory() { 
    fonts = new Font[3]; 
    // font[0] = largest font 
    // font[1] = middle font 
    // font[2] = smallest font 
    } 

    public Font getFont(String string, Graphics g, Rectangle rectangle) { 
    for (Font font : fonts) { 
     Rectangle2D bounds = g.getFontMetrics(font).getStringBounds(string, g); 
     if (rectangle.contains(bounds)) { 
     return font; 
     } 
    } 

    return fonts[fonts.length - 1]; 
    } 
} 
相关问题