java - 如何将像素转换为dp?

标签 java android pixel density-independent-pixel

我正在尝试用 Java 创建一个简单的 Android 应用程序,但我遇到了障碍。

我有一个包含许多位图的数组列表,我正在将它们绘制到 Canvas 上,但我正在使用像素测量,并且在大多数设备上都无法正确显示。

有什么方法可以找出我的图形的 dp 大小,并使用 dp 将其缩放到屏幕密度/大小,并使用 dp 或 dup 对其进行定位。

我的图形(正方形):

Graphic size in ldpi = 50px

Graphic size in mdpi = 75px

Graphic size in hdpi = 100px

代码中的其他所有内容都很好,除了看起来很奇怪?

如有任何帮助,我们将不胜感激。

詹姆斯。

最佳答案

来自 Android 开发者文档:

A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities

参见this了解更多信息。

关于java - 如何将像素转换为dp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9658208/

相关文章:

java - 关于 Java 7 安装

java - 读取网站列表,去掉 HTML 标签并将其全部写入 txt 文件

android - shadowOffset 在 react native android 中不起作用

android - 如何在 android 中以编程方式关闭我的应用程序?

CSS - 这些额外的 10 个像素来自哪里?

java - 从自定义 Web 服务器迁移到 apache Web 服务器

java - 如何获得实现通用接口(interface)的特定类的工厂而无需进行强制转换?

android - 从 Dropbox 下载文件并保存到 SDCARD

delphi - 检测图片中的多个形状并计算中间位置

iphone - 如何在 iPhone 上的 OpenGL ES 中设置/获取纹理上的像素?