2013-12-11 42 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之前。