Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pixels to sp

I need the current TextSize of the TextView in sp units.

But getTextSize() returns the size in pixels. So is there a way to convert pixels to sp?

like image 348
Nital Avatar asked Jun 07 '11 09:06

Nital


People also ask

What is SP in font size?

SP: is an abbreviation for Scale independent pixels. It is the same as the dp unit, but it is additionally scaled according to the user's font size selection.

How do you convert PT to SP?

There are 72 pts per inch, and 160 sp per inch (with standard font size in the device settings). this means there are 160sp per 72pts. 160sp/72pts simplifies to 20/9. So when converting pts to sp or dp use pts*20/9.

How many pixels is a dp?

One dp is a virtual pixel unit that's roughly equal to one pixel on a medium-density screen (160dpi; the "baseline" density). Android translates this value to the appropriate number of real pixels for each other density.


3 Answers

Use this

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

If you wanna test if this method works right use this snippet

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

Both TextView's font size should be same.

like image 197
sealskej Avatar answered Oct 05 '22 17:10

sealskej


See the DisplayMetrics class, it has fields for densityDpi and scaledDensity.

Example usage:

float sp = px / getResources().getDisplayMetrics().scaledDensity;
like image 36
Gabriel Negut Avatar answered Oct 05 '22 15:10

Gabriel Negut


weird to see public field that is adjusted at run time but it works. Standard Dpi is 160 so whatever your device Dpi is, say 240, both density and scaledDensity will show 240/160=1.5 This is how you convert between pixels and sp: px=1.5*sp

like image 41
Vlad Avatar answered Oct 05 '22 15:10

Vlad