Conversion between android px and dp (dip)

Source: Internet
Author: User

Method 1:

Resources resources = getResources ();

Float fPx = TypedValue. applyDimension (TypedValue. COMPLEX_UNIT_DIP, 300, resources. getDisplayMetrics ());

// Int iPx = Math. round (fPx );

// Similarly, px to dip:
Float fDip = TypedValue. applyDimension (TypedValue. COMPLEX_UNIT_PX, 300, resources. getDisplayMetrics ());
// Int iDip = Math. round (fDip );

Method 2:

/**
* Convert the cell phone resolution from dp to px (pixel)
*/
Public static int dip2px (Context context, float dpValue)
{
Final float scale = context. getResources (). getDisplayMetrics (). density;
Return (int) (dpValue * scale) + 0.5f );
}

/**
* Convert pixel to dp based on the resolution of the mobile phone
*/
Public static int px2dip (Context context, float pxValue)
{
Final float scale = context. getResources (). getDisplayMetrics (). density;
Return (int) (pxValue/scale) + 0.5f );
}

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.