Search code examples
androiddensity-independent-pixel

Convert dip to px in Android


I had written method to get the pixels from dip but it is not working. It give me runtime error.

Actually I was running this method in separate class and initialized in my Activity class

Board board = new Board(this);
board.execute(URL);

This code runs asynchronously. Please help me.

public float getpixels(int dp){
    //Resources r = boardContext.getResources();
    //float px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpis, r.getDisplayMetrics());
        
    final float scale = this.boardContext.getResources().getDisplayMetrics().density;
    int px = (int) (dp * scale + 0.5f);

    return px;
}

Solution

  • The formula is: px = dp * (dpi / 160), for having on a 160 dpi screen. See Convert dp units to pixel units for more information.

    You could try:

    public static int convertDipToPixels(float dips) {
        return (int) (dips * appContext.getResources().getDisplayMetrics().density + 0.5f);
    }
    

    Hope this helps...