将像素转换为sp

64

我需要在sp单位中获取TextView的当前TextSize

getTextSize()返回以像素为单位的大小。所以是否有一种方法可以将像素转换为sp


1
请参考此答案,了解DP -> PXPX -> DPSP to PXPX to SP的转换。 - Suragch
3个回答

146

使用这个

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

如果你想测试这个方法是否正常工作,请使用以下代码片段

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"
        />

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()));

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


48

请查看DisplayMetrics类,其中包含densityDpiscaledDensity两个字段。

使用示例:

float sp = px / getResources().getDisplayMetrics().scaledDensity;

2
仅澄清一下:DisplayMetrics类具有字段densityDpiscaledDensity,而不是方法。对于缩放,应使用density字段而不是densityDpi - Ted Hopp
请回答所问的问题。仅说出可用作答案的类的名称本身并不是一个答案。 - Megakoresh

5

看到在运行时调整的公共字段有点奇怪,但它确实有效。标准 DPI 是 160,所以无论您的设备 DPI 是多少,比如 240,密度和缩放密度都将显示 240/160=1.5。以下是像素和 sp 之间的转换方式:px=1.5*sp。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接