您需要通過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