将像素转换为sp

Nit*_*tal 53 android textview

我需要在当前TextSizeTextViewsp单位.

但是getTextSize()返回大小pixels.那有办法convert pixels to sp吗?

sea*_*kej 141

用这个

public static float pixelsToSp(Context context, float px) {
    float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
    return px/scaledDensity;
}
Run Code Online (Sandbox Code Playgroud)

如果您想测试此方法是否正常,请使用此代码段

XML

<TextView
        android:id="@+id/txtHelloWorld"
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>

<TextView
        android:id="@+id/txtHelloWorld2"
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
Run Code Online (Sandbox Code Playgroud)

Java的

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView helloWorldTextView = (TextView)    rootView.findViewById(R.id.txtHelloWorld);
TextView helloWorldTextView2 = (TextView) rootView.findViewById(R.id.txtHelloWorld2);
helloWorldTextView2.setTextSize(pixelsToSp(getActivity(), helloWorldTextView.getTextSize()));
Run Code Online (Sandbox Code Playgroud)

两个TextView的字体大小应该相同.


Gab*_*gut 35

请参阅DisplayMetrics类,它包含densityDpi和的字段scaledDensity.

用法示例:

float sp = px / getResources().getDisplayMetrics().scaledDensity;
Run Code Online (Sandbox Code Playgroud)

  • 需要澄清的是:DisplayMetrics类具有_fields_,densityDpi和scaledDensity,而不是方法。为了进行缩放,人们可能想使用“ density”字段而不是“ densityDpi”。 (2认同)

Vla*_*lad 5

很奇怪看到在运行时调整的公共字段,但它的工作原理.标准Dpi是160,所以无论你的设备Dpi是什么,比如240,密度和scaledDensity都会显示240/160 = 1.5这就是你在像素和sp之间转换的方式:px = 1.5*sp