2011-03-10 83 views
4

我有一個Android應用程序,動態縮放文本取決於Android設備的分辨率。 我已經在Android模擬器中的所有預定義分辨率上測試了此代碼,並且我的代碼正常工作。 (這包括與HTC Desire和摩托羅拉Droid相同的分辨率)在Android設備上運行時FontMetrics不正確。模擬器很好

它也適用於我的HTC Wildfire。

下面是一些屏幕截圖來自模擬器:

enter image description here enter image description here

但是...我已經試過這在HTC渴望,我已經使用摩托羅拉Droid的是,來自用戶的報告字體不正確縮放:

enter image description here

注意它是如何斬斷文字關閉。

任何想法,爲什麼這不適用於這些特定的設備?

我目前有縮放文本向下取決於可用高度爲文本的功能......是這樣的:

public static float calculateHeight(FontMetrics fm) { 

    return Math.abs(fm.ascent) + fm.descent; 

} 


public static int determineTextSize(Typeface font, float allowableHeight) { 

    Paint p = new Paint(); 
    p.setTypeface(font); 

    int size = (int) allowableHeight; 
    p.setTextSize(size); 

    float currentHeight = calculateHeight(p.getFontMetrics()); 

    while (size!=0 && (currentHeight) > allowableHeight) { 
      p.setTextSize(size--); 
     currentHeight = calculateHeight(p.getFontMetrics()); 
    } 

    if (size==0) { 
     System.out.print("Using Allowable Height!!"); 
     return (int) allowableHeight; 
    } 

    System.out.print("Using size " + size); 
    return size; 
} 

任何想法,爲什麼這是發生在只有一對夫婦的設備?以及我如何解決它? 是否還有另外一種字體指標比我在這裏需要考慮的我不知道?像Scale還是DPI?

謝謝。

回答

6

我想提兩件事情。

以我的經驗,我已經通過從FontMetrics.bottom中減去FontMetrics.top來計算字體高度(以像素爲單位)。這是由於根據Y軸的底部和頂部的正值和負值。請參閱android文檔。因此,如下我會改變你的calculateHeight方法:

public static float calculateHeight(FontMetrics fm) { 
    return fm.bottom - fm.top; 
} 

其次,你應該記住,你的determineTextSize方法將在返回的像素大小。如果您使用此設置TextView的文本大小或其他東西,那麼您應該將單位指定爲TypedValue.COMPLEX_UNIT_PX。此方法的默認單位是TypedValue.COMPLEX_UNIT_SP

+0

感謝Anupam。我不知道這兩個文字大小的單位。使用COMPLEX_UNIT_PX設置文本大小,修復了我在HTC Desire和Motorola Droid上看到的問題。非常感激。 – Sprooose 2011-05-23 01:57:08

相關問題