之前自己一直手工编写函数来实现dip值到px值,今天无意中发现android本身就带有类似的函数来实现这种转换过程,就是 TypedValue.applyDimension
public class TypedValueApiUseDemoActivity extends AppCompatActivity { public static final String TAG = "xp.chen"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_typed_value_api_use_demo); int dipValue = 20; float density = getResources().getDisplayMetrics().density; int finalPx = (int) (dipValue * density); int pxValue = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, getResources().getDisplayMetrics()); Log.i(TAG, "finalPx: "+finalPx+", pxValue: "+pxValue); } }
Log:
I/xp.chen: finalPx: 60, pxValue: 60
查看下源码,android的实现和我们自己的实现是一样的:
/** * Converts an unpacked complex data value holding a dimension to its final floating * point value. The two parameters <var>unit</var> and <var>value</var> * 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 static float applyDimension(int unit, float value, 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; }