Created
January 8, 2016 15:36
-
-
Save yichiuan/4eb7afce54e503dbaa1e to your computer and use it in GitHub Desktop.
Android:Util:Convert px dp and sp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
public class DisplayUtil { | |
public static int convertDpToPx(Context context, int dp) { | |
final float scale = context.getResources().getDisplayMetrics().density; | |
return (int) (dp * scale + 0.5f); | |
} | |
public static int convertPxToDp(Context context, int px) { | |
final float scale = context.getResources().getDisplayMetrics().density; | |
return (int) (px / scale + 0.5f); | |
} | |
public static int convertSpToPx(Context context, int sp) { | |
final float scale = context.getResources().getDisplayMetrics().scaledDensity; | |
return (int) (sp * scale + 0.5f); | |
} | |
public static int convertPxToSp(Context context, int px) { | |
final float scale = context.getResources().getDisplayMetrics().scaledDensity; | |
return (int) (px / scale + 0.5f); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment