Skip to content

Instantly share code, notes, and snippets.

@alphamu
Last active February 24, 2020 16:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save alphamu/7520639 to your computer and use it in GitHub Desktop.
Save alphamu/7520639 to your computer and use it in GitHub Desktop.
Android - DIP to PX or PX to DIP
public static int dpToPx(Context context, int dp) {
Resources r = context.getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
return (int) px;
}
public static int pxToDp(Context context, int px) {
final float scale = context.getResources().getDisplayMetrics().density;
int dp = (int) (px * scale + 0.5f);
return dp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment