Android 将 Px 转换为 Dp(视频纵横比) [英] Android Convert Px to Dp (Video Aspect Ratio)

查看:23
本文介绍了Android 将 Px 转换为 Dp(视频纵横比)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
在android中将像素转换为dp

我正在尝试将像素转换为 dp.公式是什么?

I'm trying to convert pixels to dp. What is the formula?

让我们将 640 和 480 转换为 dp.文档是这样说的

Lets convert 640 and 480 into dp. The docs say this

dp单位到屏幕像素的转换很简单:px = dp * (dpi/160)

The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160)

但我认为这不是我需要的(而且我不知道如何使用它).我想我只需要论坛.我已经准备好了代码:

But I don't think that is what I need (and I don't know how to use this). I guess I just need the forumla. I have the code ready:

DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    switch(metrics.densityDpi)
    {
         case DisplayMetrics.DENSITY_LOW:
         int sixForty = ?
         int fourEighty = ?
         break;

         case DisplayMetrics.DENSITY_MEDIUM:
         int sixForty = ?
         int fourEighty = ?
         break;

         case DisplayMetrics.DENSITY_HIGH:
         int sixForty = ?
         int fourEighty = ?
         break;
    }

推荐答案

与其尝试从屏幕的密度分类中推断dp转换因子,您可以直接查询:

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 然后将包含您需要乘以 dp 以获得设备屏幕的物理像素尺寸的因子.

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);

这篇关于Android 将 Px 转换为 Dp(视频纵横比)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆