Skip to content

Instantly share code, notes, and snippets.

@TakWolf
Created January 4, 2015 08:25
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TakWolf/fed84366d646d33749cd to your computer and use it in GitHub Desktop.
Save TakWolf/fed84366d646d33749cd to your computer and use it in GitHub Desktop.
Android px, sp, dp convert util
package com.takwolf.android.util;
import android.content.Context;
public class DisplayUtil {
/**
* 将px值转换为dip或dp值,保证尺寸大小不变
*/
public static int px2dip(Context context, float pxValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* 将dip或dp值转换为px值,保证尺寸大小不变
*/
public static int dip2px(Context context, float dipValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
/**
* 将px值转换为sp值,保证文字大小不变
*/
public static int px2sp(Context context, float pxValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
/**
* 将px值转换为sp值,保证文字大小不变
*/
public static int sp2px(Context context, float spValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
}
@edujjalvarez
Copy link

no entiendo está todo en japonés.

@BuYishi
Copy link

BuYishi commented Jul 21, 2019

Nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment