简体   繁体   中英

Android Paint. How is the character width calculated?

I need to know how the width of text changes when I increase paint.getTextSize() n times. I thought that is proportional, but first test indicates that it is not. I got result like below, where

  • 1st number - size of text set by Paint.setTextSize(float)

  • 2nd number - width of text measured with Paint.measureText(String)

     1;1.0 2;1.0 3;2.0 4;2.0 5;3.0 6;3.0 7;4.0 8;4.0 9;5.0 10;5.0 11;6.0 12;7.0 13;7.0 14;8.0 15;8.0 16;9.0 17;9.0 18;10.0 19;10.0 20;11.0 21;11.0 22;12.0 23;13.0 24;13.0 25;14.0 26;14.0 27;15.0 28;15.0 29;16.0 30;16.0 31;17.0 32;17.0 33;18.0 34;19.0 35;19.0 36;20.0 37;20.0 38;21.0 39;21.0 40;22.0 41;22.0 42;23.0 43;23.0 44;24.0 45;24.0 46;25.0 47;26.0 48;26.0 49;27.0 50;27.0 51;28.0 52;28.0 53;29.0

Is it possible to calculate how the text width would change after changing text size n times?
I don't want to use Paint.measureText(String) method ever time i change size, because it's bad for performance.
Thanks in advance!

See Getting height of text view before rendering to layout . Maybe it will measure text faster. An example for height is below.

public static int getHeight(TextView t) {
    int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(screenWidth(t.getContext()), View.MeasureSpec.AT_MOST);
    int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    t.measure(widthMeasureSpec, heightMeasureSpec);
    return t.getMeasuredHeight();
}

public static int screenWidth(Context context)
{
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    return display.getWidth();
}

Also you can try to estimate a formula of changing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM