將像素轉換爲sp
回答
請參閱DisplayMetrics類,它的字段爲densityDpi
和scaledDensity
。
用法示例:
float sp = px/getResources().getDisplayMetrics().scaledDensity;
只是爲了澄清:'DisplayMetrics'類具有_fields_' densityDpi'和'scaledDensity',而不是方法。而對於縮放,人們會想要使用'density'字段而不是'densityDpi'。 – 2016-04-12 16:58:24
請回答提問的問題。說一個可以用於答案的類的名字本身並不是一個答案。 – Megakoresh 2016-12-16 12:50:30
使用此
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的字體大小都應該相同。
奇怪的是看到在運行時調整的公共字段,但它的工作原理。標準Dpi是160,所以無論你的設備Dpi是240,密度和比例密度都會顯示240/160 = 1.5 這就是你如何在像素和sp之間進行轉換:px = 1.5 * sp
- 1. 將mm轉換爲像素
- 2. Android:如何將px轉換爲sp
- 3. 如何將pt轉換爲sp?
- 4. 將屏幕轉換爲SP 4326
- 5. 將DOM元素轉換爲圖像?
- 6. 如何將像素轉換爲CGFloat?
- 7. 如何將像素轉換爲dp?
- 8. 將像素轉換爲分鐘
- 9. 將座標轉換爲像素座標
- 10. 將像素轉換爲畫布
- 11. 將像素轉換爲多邊形
- 12. 將2D像素數組轉換爲BufferedImage
- 13. 嘗試將Facebook像素轉換爲HTML
- 14. Android:將點轉換爲像素
- 15. CSS將百分比轉換爲像素
- 16. 將Drawing.Bitmap轉換爲Imaging.Metafile - 像素完美
- 17. Aforge,將像素數據轉換爲UnmanagedImage
- 18. X11:將像素值轉換爲RGB
- 19. 將像素轉換爲電子版
- 20. Android將像素轉換爲inchec,毫米
- 21. 將像素值轉換爲RGB格式
- 22. 如何將LOGFONT.lfHeight轉換爲像素?
- 23. 轉換像素爲cm
- 24. 如何將Bgr像素轉換爲EmguCV中的Hsv像素?
- 25. 將內部透明像素轉換爲白色像素
- 26. 像素到像素轉換
- 27. 轉換像素
- 28. 旋轉LAT,已轉換爲像素
- 29. 將ElementTree轉換爲元素
- 30. 將XML轉換爲XML,將屬性轉換爲元素
另請參閱[this answer] (http://stackoverflow.com/a/42108115/3681880)爲'DP - > PX','PX - > DP','SP到PX'和'PX到SP'轉換。 – Suragch 2017-02-08 08:37:32