有没有办法确定 Android 物理屏幕高度(以厘米或英寸为单位)?

发布于 2024-08-20 07:08:05 字数 97 浏览 7 评论 0原文

我需要确切地知道设备上的屏幕有多大(以实际长度单位表示),以便我可以计算重力加速度(以每毫秒像素为单位)。

Android API 中有一个方法可以实现这一点吗?

I need to know exactly how big the screen is on the device in real units of length so I can calculate the acceleration due to gravity in pixels per millisecond.

Is there a method somewhere in the Android API for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

影子是时光的心 2024-08-27 07:08:06

以下代码片段将帮助您获取屏幕尺寸(以英寸为单位)

public static double getScreenSizeInches(Activity activity){
    WindowManager windowManager = activity.getWindowManager();
    Display display = windowManager.getDefaultDisplay();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    display.getMetrics(displayMetrics);

    // since SDK_INT = 1;
    int mWidthPixels = displayMetrics.widthPixels;
    int mHeightPixels = displayMetrics.heightPixels;

    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) {
        try{
            mWidthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
            mHeightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
        } catch (Exception ignored) {}
    }

    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 17) {
        try {
            Point realSize = new Point();
            Display.class.getMethod("getRealSize", Point.class).invoke(display, realSize);
            mWidthPixels = realSize.x;
            mHeightPixels = realSize.y;
        } catch (Exception ignored) {}
    }

    DisplayMetrics dm = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(mWidthPixels / dm.xdpi, 2);
    double y = Math.pow(mHeightPixels / dm.ydpi, 2);
    return Math.sqrt(x + y);
}

希望有所帮助。

Following code snippet will help you to get Screen Size in Inches

public static double getScreenSizeInches(Activity activity){
    WindowManager windowManager = activity.getWindowManager();
    Display display = windowManager.getDefaultDisplay();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    display.getMetrics(displayMetrics);

    // since SDK_INT = 1;
    int mWidthPixels = displayMetrics.widthPixels;
    int mHeightPixels = displayMetrics.heightPixels;

    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) {
        try{
            mWidthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
            mHeightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
        } catch (Exception ignored) {}
    }

    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 17) {
        try {
            Point realSize = new Point();
            Display.class.getMethod("getRealSize", Point.class).invoke(display, realSize);
            mWidthPixels = realSize.x;
            mHeightPixels = realSize.y;
        } catch (Exception ignored) {}
    }

    DisplayMetrics dm = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(mWidthPixels / dm.xdpi, 2);
    double y = Math.pow(mHeightPixels / dm.ydpi, 2);
    return Math.sqrt(x + y);
}

Hope this help.

通知家属抬走 2024-08-27 07:08:06

我已经尝试了其他答案中提到的大多数方法,但这些方法在特定设备上失败。这是我对解决这个问题的一些贡献。该代码是用 Kotlin 编写的

获取 DisplayMetrics 对象:

    val manager = mContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val displayMetrics = DisplayMetrics()
    manager.getDefaultDisplay().getMetrics(displayMetrics)

计算以英寸为单位的屏幕宽度,如下所示:

    val widthInDotPoints : Double = (displayMetrics.widthPixels * (160 * 1.0 /displayMetrics.densityDpi))
    val widthInInches : Double = width / displayMetrics.xdpi

在这里,我使用 widthPixels 以点点数 (dp) 计算设备的宽度,然后将其转换为以英寸为单位的宽度。我使用 160 .ie DisplayMetrics.DENSITY_MEDIUM 作为转换因子将 widthPixels 转换为 widthInDotPoints。

同样,计算屏幕高度(以英寸为单位):

    val heightInDotPoints : Double = (displayMetrics.heightPixels * (160 * 1.0 /displayMetrics.densityDpi))
    val heightInInches : Double = height / displayMetrics.ydpi

I have tried most of the ways mentioned in the other answers, but those methods fail on particular devices. So here is bit of my contribution to solving this problem. The code is written in Kotlin

Get the DisplayMetrics object :

    val manager = mContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val displayMetrics = DisplayMetrics()
    manager.getDefaultDisplay().getMetrics(displayMetrics)

Calculate the Screen width in inches as follows :

    val widthInDotPoints : Double = (displayMetrics.widthPixels * (160 * 1.0 /displayMetrics.densityDpi))
    val widthInInches : Double = width / displayMetrics.xdpi

Here, I have calculated the width of device in terms of dot points(dp) using widthPixels and then converted it to width in terms of inches. I have used 160 .i.e DisplayMetrics.DENSITY_MEDIUM as conversion factor to convert the widthPixels to widthInDotPoints.

Similarly, calculate the Screen Height in inches :

    val heightInDotPoints : Double = (displayMetrics.heightPixels * (160 * 1.0 /displayMetrics.densityDpi))
    val heightInInches : Double = height / displayMetrics.ydpi
渡你暖光 2024-08-27 07:08:06

我用它来获取实际尺寸

final DisplayMetrics metrics = new DisplayMetrics();
final WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    windowManager.getDefaultDisplay().getRealMetrics(metrics);
}
else {
    windowManager.getDefaultDisplay().getMetrics(metrics);
}
int realHeight = metrics.heightPixels; // This is real height
int realWidth = metrics.widthPixels; // This is real width

I used this to get the real size

final DisplayMetrics metrics = new DisplayMetrics();
final WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    windowManager.getDefaultDisplay().getRealMetrics(metrics);
}
else {
    windowManager.getDefaultDisplay().getMetrics(metrics);
}
int realHeight = metrics.heightPixels; // This is real height
int realWidth = metrics.widthPixels; // This is real width
一桥轻雨一伞开 2024-08-27 07:08:06

有些设备(例如像素)返回的 xdpi、ydpi 不正确。
所以你可以根据密度来计算。

fun getScreenSizeInInches(context: Context): Float {
    try {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            context.display
        } else {
            windowManager.defaultDisplay
        }

        val metrics = DisplayMetrics()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            display?.getRealMetrics(metrics)
        } else {
            display?.getMetrics(metrics)
        }
        // Calculate the diagonal size in inches using Pythagorean theorem
        var xdpi = metrics.xdpi
        if (xdpi < 160) {
            xdpi = getDPIFromDensity(metrics.density)
        }
        var ydpi = metrics.ydpi
        if (ydpi < 160) {
            ydpi = getDPIFromDensity(metrics.density)
        }
        val widthInInches = metrics.widthPixels / xdpi
        val heightInInches = metrics.heightPixels / ydpi
        val diagonalInInches = sqrt(widthInInches.pow(2) + heightInInches.pow(2))
        Log.d("diagonalInInches", metrics.toString() + "\n" + diagonalInInches.toString())
        return diagonalInInches
    } catch (e: Exception) {
        return 6.0f
    }
}

/*
* Some device pixel return xdpi, ydpi not correct.
* */
private fun getDPIFromDensity(density: Float): Float {
    val dpi = 160 * density
    Log.d("getDPIFromDensity", dpi.toString())
    return dpi
}

Some device like pixel return xdpi, ydpi not correct.
So you can calculator base on density.

fun getScreenSizeInInches(context: Context): Float {
    try {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            context.display
        } else {
            windowManager.defaultDisplay
        }

        val metrics = DisplayMetrics()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            display?.getRealMetrics(metrics)
        } else {
            display?.getMetrics(metrics)
        }
        // Calculate the diagonal size in inches using Pythagorean theorem
        var xdpi = metrics.xdpi
        if (xdpi < 160) {
            xdpi = getDPIFromDensity(metrics.density)
        }
        var ydpi = metrics.ydpi
        if (ydpi < 160) {
            ydpi = getDPIFromDensity(metrics.density)
        }
        val widthInInches = metrics.widthPixels / xdpi
        val heightInInches = metrics.heightPixels / ydpi
        val diagonalInInches = sqrt(widthInInches.pow(2) + heightInInches.pow(2))
        Log.d("diagonalInInches", metrics.toString() + "\n" + diagonalInInches.toString())
        return diagonalInInches
    } catch (e: Exception) {
        return 6.0f
    }
}

/*
* Some device pixel return xdpi, ydpi not correct.
* */
private fun getDPIFromDensity(density: Float): Float {
    val dpi = 160 * density
    Log.d("getDPIFromDensity", dpi.toString())
    return dpi
}
初熏 2024-08-27 07:08:06

您需要使用屏幕密度来计算此值。

Context.getResources().getDisplayMetrics().density

根据文档:

显示的逻辑密度。这是密度独立像素单元的缩放因子,其中一个 DIP 是大约 160 dpi 屏幕(例如 240x320、1.5"x2" 屏幕)上的一个像素,提供系统显示的基线。因此,在 160dpi 屏幕上,该密度值为 1;在 120 dpi 屏幕上,该值为 0.75;等等

此值并不完全遵循实际屏幕尺寸(由 xdpi 和 ydpi 给出),而是用于根据显示 dpi 的总体变化逐步缩放整个 UI 的尺寸。例如,240x320 屏幕即使其宽度为 1.8"、1.3" 等,密度也将为 1。但是,如果屏幕分辨率增加到 320x480 但屏幕尺寸仍为 1.5"x2",则密度将增加(可能增加到 1.5)。

You need to use the screen density to calculate this.

Context.getResources().getDisplayMetrics().density

According to the documentation:

The logical density of the display. This is a scaling factor for the Density Independent Pixel unit, where one DIP is one pixel on an approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen), providing the baseline of the system's display. Thus on a 160dpi screen this density value will be 1; on a 120 dpi screen it would be .75; etc.

This value does not exactly follow the real screen size (as given by xdpi and ydpi, but rather is used to scale the size of the overall UI in steps based on gross changes in the display dpi. For example, a 240x320 screen will have a density of 1 even if its width is 1.8", 1.3", etc. However, if the screen resolution is increased to 320x480 but the screen size remained 1.5"x2" then the density would be increased (probably to 1.5).

半步萧音过轻尘 2024-08-27 07:08:05

使用以下内容:

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(mWidthPixels/dm.xdpi,2);
    double y = Math.pow(mHeightPixels/dm.ydpi,2);
    double screenInches = Math.sqrt(x+y);
    Log.d("debug","Screen inches : " + screenInches);

当从下面的代码中获取 mWidthPixels 和 mHeightPixels 时

private void setRealDeviceSizeInPixels()
{
    WindowManager windowManager = getWindowManager();
    Display display = windowManager.getDefaultDisplay();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    display.getMetrics(displayMetrics);


    // since SDK_INT = 1;
    mWidthPixels = displayMetrics.widthPixels;
    mHeightPixels = displayMetrics.heightPixels;

    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
    {
        try
        {
            mWidthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
            mHeightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
        }
        catch (Exception ignored)
        {
        }
    }

    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 17)
    {
        try
        {
            Point realSize = new Point();
            Display.class.getMethod("getRealSize", Point.class).invoke(display, realSize);
            mWidthPixels = realSize.x;
            mHeightPixels = realSize.y;
        }
        catch (Exception ignored)
        {
        }
    }

请参阅此帖子以供参考:
获取屏幕尺寸(以像素为单位)

Use the following:

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(mWidthPixels/dm.xdpi,2);
    double y = Math.pow(mHeightPixels/dm.ydpi,2);
    double screenInches = Math.sqrt(x+y);
    Log.d("debug","Screen inches : " + screenInches);

When mWidthPixels and mHeightPixels are taken from below code

private void setRealDeviceSizeInPixels()
{
    WindowManager windowManager = getWindowManager();
    Display display = windowManager.getDefaultDisplay();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    display.getMetrics(displayMetrics);


    // since SDK_INT = 1;
    mWidthPixels = displayMetrics.widthPixels;
    mHeightPixels = displayMetrics.heightPixels;

    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
    {
        try
        {
            mWidthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
            mHeightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
        }
        catch (Exception ignored)
        {
        }
    }

    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 17)
    {
        try
        {
            Point realSize = new Point();
            Display.class.getMethod("getRealSize", Point.class).invoke(display, realSize);
            mWidthPixels = realSize.x;
            mHeightPixels = realSize.y;
        }
        catch (Exception ignored)
        {
        }
    }

See this post for reference:
Get screen dimensions in pixels

咿呀咿呀哟 2024-08-27 07:08:05

要获取当前大小,请在最后使用 Math.round 。

 DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(dm.widthPixels/dm.xdpi,2);
    double y = Math.pow(dm.heightPixels/dm.ydpi,2);
    double screenInches = Math.sqrt(x+y);
    Log.d("debug","Screen inches : " + screenInches);

screenInches=  (double)Math.round(screenInches * 10) / 10;

for getting the current size use Math.round at the end.

 DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(dm.widthPixels/dm.xdpi,2);
    double y = Math.pow(dm.heightPixels/dm.ydpi,2);
    double screenInches = Math.sqrt(x+y);
    Log.d("debug","Screen inches : " + screenInches);

screenInches=  (double)Math.round(screenInches * 10) / 10;
感性不性感 2024-08-27 07:08:05

Android 开发者屏幕信息。

使用 xdpi * widthPixels 和 ydpi * heightPixels 可能会得到你想要的东西,我想。

android developers screen info.

use xdpi * widthPixels and ydpi * heightPixels might get you what you want i think.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文