基于ppi的像素到dp转换器



我正在为给定的图形转换px到dp。浏览文档时,我注意到480ppi屏幕(xxhdpi)的1dp = 3px。

我正在红米Note3上测试它,它的ppi大约是403。

我的设计师提供了以像素为单位的边距。我应该把它们转换成像素,使用1:3的比例吗?还是应该是不同的

/**
 * This method converts dp unit to equivalent pixels, depending on device density. 
 * 
 * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
 * @param context Context to get resources and device specific display metrics
 * @return A float value to represent px equivalent to dp depending on device density
 */
public static float convertDpToPixel(float dp, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return px;
}
/**
 * This method converts device specific pixels to density independent pixels.
 * 
 * @param px A value in px (pixels) unit. Which we need to convert into db
 * @param context Context to get resources and device specific display metrics
 * @return A float value to represent dp equivalent to px value
 */
public static float convertPixelsToDp(float px, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return dp;
}

有关更多信息,请查看此SOF post将像素转换为dp

相关内容

  • 没有找到相关文章

最新更新