Sunday 21 September 2014

Android: methods for converting pixels to scaled pixels, and vice versa

Here's a couple of methods for converting from pixels to scaled pixels (for use in TextViews to set the size of text), and vice versa.

If you need to convert between pixels and density-independent pixels, then you need these methods instead:
http://adilatwork.blogspot.co.uk/2011/09/android-methods-for-converting-density.html
/**  
  * @param scaledPixels  
  * @return the number of pixels which scaledPixels corresponds to  
  * on the device.  
  */  
 private float convertSpToPx(float scaledPixels) {  
  DisplayMetrics dm = getContext().getResources().getDisplayMetrics();  
  return scaledPixels * dm.scaledDensity;  
 }  
   
 /**  
  * @param pixels  
  * @return the number of scaled pixels which pixels corresponds to  
  * on the device.  
  */  
 private float convertPxToSp(float pixels) {  
  DisplayMetrics dm = getContext().getResources().getDisplayMetrics();  
  return pixels / dm.scaledDensity;  
 }

No comments: