将像素转换为 dp [英] Converting pixels to dp

查看:37
本文介绍了将像素转换为 dp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为分辨率为 480x800 的 Pantech 设备创建了高度和宽度(以像素为单位)的应用程序.

I have created my application with the height and width given in pixels for a Pantech device whose resolution is 480x800.

我需要为 G1 设备转换高度和宽度.
我认为将其转换为 dp 将解决问题并为两种设备提供相同的解决方案.

I need to convert height and width for a G1 device.
I thought converting it into dp will solve the problem and provide the same solution for both devices.

有没有什么简单的方法可以将像素转换为dp?
有什么建议吗?

Is there any easy way to convert pixels to dp?
Any suggestions?

推荐答案

Java 代码:

// Converts 14 dip into its equivalent px
float dip = 14f;
Resources r = getResources();
float px = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,
    dip,
    r.getDisplayMetrics()
);

Kotlin 代码:

 val dip = 14f
 val r: Resources = resources
 val px = TypedValue.applyDimension(
     TypedValue.COMPLEX_UNIT_DIP,
     dip,
     r.displayMetrics
 )

Kotlin 扩展:

val Number.toPx get() = TypedValue.applyDimension(
  TypedValue.COMPLEX_UNIT_DIP,
  this.toFloat(),
  Resources.getSystem().displayMetrics)

这篇关于将像素转换为 dp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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