Android Convert Px to Dp (Video Aspect Ratio) [duplicate]

Instead of trying to infer the dp conversion factor from the screen’s density classification, you can simply query it directly:

getWindowManager().getDefaultDisplay().getMetrics(metrics);
float logicalDensity = metrics.density;

logicalDensity will then contain the factor you need to multiply dp by to get physical pixel dimensions for the device screen.

int px = (int) Math.ceil(dp * logicalDensity);

Leave a Comment