2013-12-11 108 views
6

我的應用程序能夠準確測量字符串是至關重要的;我一直在使用Paint.measureText()來做到這一點。不幸的是,在4.4中,這個方法被更改爲不再返回一個精確值,而是返回一個四捨五入的值。有人知道我可以使用另一種方法來精確測量文本,或有任何其他建議嗎?Android:在4.4中,Paint.measureText()不向後兼容。任何解決方法?

Android的源:

Android 17 
    return w*mInvCompatScaling; 
Android 18 
    return (float) Math.ceil(w*mInvCompatScaling); 
+0

您可能可以使用反射來訪問mInvCompatScaling和native_measureText。 – njzk2

+0

Yikes,這是一個非常重要的變化,真的感覺像一個問題:https://github.com/android/platform_frameworks_base/commit/8e04840f38a16f806754dfca3de50c2548e67913。您是否嘗試過通過反射調用'native_measureText',如njzk2所示? – CodingIntrigue

+2

出於好奇,文字長度的亞像素測量的用例是什麼?也許還有其他的解決方案來解決你的大用例。 – CommonsWare

回答

0

它看起來回落至反射找回舊功能的唯一途徑。如下查找私有本地方法並調用它。

Paint paint = new Paint(); 
// configure paint here 

Method m = paint.getClass().getDeclaredMethod("native_measureText", 
       String.class, int.class); 
float size = m.invoke(paint, text, 0x2); 
      // text - text to measure 
      // 0x2 - default for Right-To-Left text 

雖然它看起來不太乾淨,但它必須適合你。

0

您必須設置:

m.setAccessible(true); 

調用它不要讓IllegalAccessException之前。