Convert between DP and PX in Android

Source: Internet
Author: User

Once in the process of processing pictures encountered such a situation: millet big screen mobile phone on a variety of friendly display, but in Samsung mobile phones, all kinds of disorder, dislocation phenomenon.

Of course, distance units with DP, text units with SP, which we all know! In the layout file we used DP, which actually requires us to dynamically change these values, but many controls do not support DP. At this point we need to convert the DP value into PX.

Note: To convert the DP value to PX, I was wrong here. Not to mention, directly on the realization:

public class Displayutils {private static displaymetrics sdisplaymetrics;    Private static final float round_difference = 0.5f; /** * Initialization Operation * * @param context Context */public static void init (context context) {Sdisplaymet    RICS = Context.getresources (). Getdisplaymetrics (); /** * Get screen width unit: Pixel * * @return screen width */public static int getwidthpixels () {return sdisplay    Metrics.widthpixels; /** * Get screen height units: pixels * * @return Screen Height */public static int getheightpixels () {return sdispla    Ymetrics.heightpixels; /** * Get screen width units: pixels * * @return Screen width */public static float getdensity () {return sdisplayme    trics.density;        }/** * DP to PX * * @param DP DP value * @return converted pixel value */public static int dp2px (int dp) {    return (int) (DP * sdisplaymetrics.density + round_difference); }/** * DP to PX * * @param DP DP value * @return ConversionThe pixel value after */public static float dp2px (float DP) {return DP * sdisplaymetrics.density + round_difference;        }/** * PX to DP * * @param px px value * @return converted DP Value */public static int px2dp (int px) {    return (int) (px/sdisplaymetrics.density + round_difference); }
This little knowledge is hoping to help you!

Convert between DP and PX in Android

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.