您需要通过DisplayMetrics还是怎么过让屏幕宽度...
为了得到字符大小使用带边界的绘画进行计算。
characterWidth/screenWidth = characterScreenPercentage
我做了一个双,但你可以很容易地将其更改为浮动。
对于人物:
public Double characterToScreenWidthPercentage(Character c) {
Paint paint = new Paint();
Rect boundA = new Rect();
DisplayMetrics metrics = new DisplayMetrics();
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay().getMetrics(metrics);
paint.getTextBounds(Character.toString(c), 0, 1, boundA);
Log.v("fn", Integer.toString(boundA.width()));
Log.v("fn", Integer.toString(metrics.widthPixels));
Log.v("fn", Double.toString((float) boundA.width()/(float) metrics.widthPixels));
return ((double) boundA.width()/(double) metrics.widthPixels);
}
对于字符串:
public Double stringToScreenWidthPercentage(String str) {
Paint paint = new Paint();
Rect boundA = new Rect();
DisplayMetrics metrics = new DisplayMetrics();
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay().getMetrics(metrics);
paint.getTextBounds(str, 0, 1, boundA);
Log.v("fn", Integer.toString(boundA.width()));
Log.v("fn", Integer.toString(metrics.widthPixels));
Log.v("fn", Double.toString((float) boundA.width()/(float) metrics.widthPixels));
return ((double) boundA.width()/(double) metrics.widthPixels);
}
@CrandellWS帮助我理解,你究竟想从这个问题到底究竟是什么?是不是只是通过getWindowManager()。getDefaultDisplay()。getMetrics(度量))来计算屏幕宽度并将测量的文本宽度除以它? (关于你提到的你自己的问题,只需根据'dp'的屏幕宽度设置fontSize) –
我试图吸引人们关注我自己的问题 - > http://stackoverflow.com/questions/35117278/canvas-drawtext -with-pixel-perfect-t在画布上,我解决了这个问题,您可以使用该解决方案为此问题创建答案。声誉对我来说不是非常重要,所以请随时收集简单的50 ... – CrandellWS
@GideonKain你可以使用布局百分比支持库,并可以给小部件提供百分比。你可以在这里查看样品。 http://www.androidauthority.com/using-the-android-percent-support-library-630715/ – androidnoobdev