Android - pixels to dips

后端 未结 4 1923
我寻月下人不归
我寻月下人不归 2020-12-10 08:07

I have an image of a face (250px X 250px) that is in an absolute layout element. I currently get the user\'s touch coordinates and using some maths calculate what has been t

相关标签:
4条回答
  • 2020-12-10 08:48

    pixels = dps * (density / 160)

    The (density / 160) factor is known as the density scale factor, and get be retrieved in Java from the Display Metrics object. What you should do is store the position of the nose etc in terms of dips (which are the same as pixels on a screen with density 160), and then convert dips to pixels depending on what screen you are running on:

    final static int NOSE_POSITION_DP = 10;
    final float scale = getContext().getResources().getDisplayMetrics().density;
    final int nosePositionPixels = (int) (NOSE_POSITION_DP * scale + 0.5f);
    
    0 讨论(0)
  • 2020-12-10 08:55

    A very simple way of doing this.

    int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 250, (mContext).getResources().getDisplayMetrics());
    
    0 讨论(0)
  • 2020-12-10 09:12

    I have three useful functions in my library...

    get Screen Density

    public static float getDensity(Context context){
        float scale = context.getResources().getDisplayMetrics().density;       
        return scale;
    }
    

    convert Dip to Pixels.

    public static int convertDiptoPix(int dip){
        float scale = getDensity();
        return (int) (dip * scale + 0.5f);
    }
    

    convert Pixels to Dips.

    public static int convertPixtoDip(int pixel){
        float scale = getDensity();
        return (int)((pixel - 0.5f)/scale);
    }
    
    0 讨论(0)
  • 2020-12-10 09:14
    public int getDip(int pixel)
    {
            float scale = getBaseContext().getResources().getDisplayMetrics().density;
            return (int) (pixel * scale + 0.5f);
     }
    
    0 讨论(0)
提交回复
热议问题