http://shareandopen.tumblr.com/post/20110980401/android-util-typedvalue-applydimension#
[Android] - 官方轉換dp, sp 至 pixel的函式
在寫Android Custom的View時,多多少少會在程式碼當中去轉換你的圖片、元件、文字的大小
但是Android程式碼只認得Pixel,而Android Design的原則是希望大家能夠在元件大小用dp為主,而文字大小則用sp為主。網路上也很多dp轉pixel的程式碼。但如果還是覺得不保險,可以試試官方轉換各種類型至pixel的函式:TypedValue.applyDimension,是在android.util這個package下面。原始碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
/**
* Converts an unpacked complex data value holding a dimension to its final floating * point value. The two parametersunit andvalue* are as in {@link #TYPE_DIMENSION}. * * @param unit The unit to convert from. * @param value The value to apply the unit to. * @param metrics Current display metrics to use in the conversion -- * supplies display density and scaling information. * * @return The complex floating point value multiplied by the appropriate * metrics depending on its unit. */ public float applyDimension( int unit, float
DisplayMetrics metrics) { switch (unit) { case COMPLEX_UNIT_PX: return value; case COMPLEX_UNIT_DIP: return value * metrics.density; case COMPLEX_UNIT_SP: return value * metrics.scaledDensity; case COMPLEX_UNIT_PT: return value * metrics.xdpi * ( 1 .0f/ 72 ); case COMPLEX_UNIT_IN: return value * metrics.xdpi; case COMPLEX_UNIT_MM: return value * metrics.xdpi * ( 1 .0f/ 25 .4f); } return 0 ; } |
那要怎麼使用了,很簡單,請參考以下作法,此範例是說明如何將20dp轉換成實際的Pixel
1
2
3
4
|
Resources r = context.getResources(); // 取得手機資源 float
//轉換dp值 20 , //dp值 r.getDisplayMetrics()); |