2011-05-23 67 views

回答

7

如果你看一下字體(這是OpenJDK的)的源代碼,以名稱,樣式,尺寸的構造都顯得輕巧:

public Font(String name, int style, int size) { 
    this.name = (name != null) ? name : "Default"; 
    this.style = (style & ~0x03) == 0 ? style : 0; 
    this.size = size; 
    this.pointSize = size; 
} 

然而,這需要一個文件,fontformat構造函數是:

private Font(File fontFile, int fontFormat, 
      boolean isCopy, CreatedFontTracker tracker) 
    throws FontFormatException { 
    this.createdFont = true; 
    /* Font2D instances created by this method track their font file 
    * so that when the Font2D is GC'd it can also remove the file. 
    */ 
    this.font2DHandle = 
     FontManager.createFont2D(fontFile, fontFormat, 
           isCopy, tracker).handle; 
    this.name = this.font2DHandle.font2D.getFontName(Locale.getDefault()); 
    this.style = Font.PLAIN; 
    this.size = 1; 
    this.pointSize = 1f; 
} 

這顯然是重量級(具體FontManager.createFont2D(...)一部分。此構造僅由Font.createFont()使用。

全部測試l,如果您使用的是系統中的字體,那麼您沒有問題,只需創建它並按名稱引用即可。如果你提供自己的字體(即:從TrueType文件),你可能會更好的緩存它。 (也就是說,IIRC,有一種方法可以簡單地將文件加載到AWT的緩存中,以便您可以簡單地引用它的名稱。)

深入挖掘源代碼,所有函數(如getFamily(),getFontName (),getNumGlyphs(),首先調用getFont2D(),它基本上是:

private Font2D getFont2D() { 
    // snip 
    if (font2DHandle == null) { 
     font2DHandle = 
      FontManager.findFont2D(name, style, 
            FontManager.LOGICAL_FALLBACK).handle; 
    } 
    /* Do not cache the de-referenced font2D. It must be explicitly 
    * de-referenced to pick up a valid font in the event that the 
    * original one is marked invalid 
    */ 
    return font2DHandle.font2D; 
} 

左右,即示出了每個字體絕對重量輕,而且它拉從FontManager它負責緩存字體的必要信息。