Android Unit conversion (Conversion tool class between PX, DP, SP)

Source: Internet
Author: User

In Android development, when it comes to screen video problems, the conversion between PX, DP, SP is an important part, so Yang Brother a tool class for everyone.

Package com.zw.express.tool;


Import Android.content.Context;
Import Android.util.DisplayMetrics;
/**
* YDC
* @author Administrator
*
*/
public class Densityutils {
/**
* Switch from Dip unit to PX (pixel) According to the resolution of the phone
*/
public static int dp2px (context context, float Dpvalue) {
Displaymetrics DM = context.getresources (). Getdisplaymetrics ();
Final float scale = dm.density;
return (int) (Dpvalue * scale + 0.5f);
}


/**
* According to the resolution of the phone from PX (pixel) to the unit to become DP
*/
public static float PX2DP (context context, float Pxvalue) {
Displaymetrics DM = context.getresources (). Getdisplaymetrics ();
Final float scale = dm.density;
Return (pxvalue-0.5f)/scale;
}


/**
* Convert PX value to SP value, keep text size unchanged
*/
public static int PX2SP (context context, float Pxvalue) {
Final float Fontscale = context.getresources (). Getdisplaymetrics (). scaleddensity;
return (int) (Pxvalue/fontscale + 0.5f);
}


/**
* Convert SP value to PX value, keep text size unchanged
*/
public static int sp2px (context context, float Spvalue) {
Final float Fontscale = context.getresources (). Getdisplaymetrics (). scaleddensity;
return (int) (Spvalue * fontscale + 0.5f);
}
}

Android Unit conversion (Conversion tool class between PX, DP, SP)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.