I want the fonts of different devices to be exactly the same size, so I chose to use pt.
But with a lot of different resolution virtual devices try to find the same PT display font size is not the same
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = findViewById(R.id.textView);
String tx = "123456";
tv.setText(tx);
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, pt2px(this, 50));
tv.setBackgroundColor(Color.RED);
tv.setGravity(Gravity.CENTER);
}
public static int pt2px(Context context, float ptValue) {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(dm);
final float fontScale = dm.xdpi;
return (int) (ptValue * (fontScale / 72f) + 0.5f);
}
}
Thank you for answering!
I have found the reason, because the DPI obtained by DisplayMetrics is set by the device manufacturer itself, not necessarily accurate. The conversion between SP and PX requires scaledDensity, and this value is also inaccurate, so the font size of some devices obtained under the same SP is also different. https://rschilling.wordpress.com/2011/02/03/android-screen-density-inaccuracies/
But I still haven't found a solution.