`

Andriod UI设计之度量单位(分辨率)说明(DIP,DP,PX,SP)

阅读更多
最近新买了个Android系统的手机来学习,把测试的项目发布在手机上发现和在虚拟机上看到的布局完全不一样。
虚拟机分辨率的选择为:HVGA  分辨率为:320*480
手机是三星i 5800的机子,分辨率为:240*400
对于我们程序开发的布局文件应该如何来做呢?
下面是布局代码:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
<ImageView
    android:id="@+id/myImageView1"
    android:layout_width="320px"
    android:layout_height="280px"
    android:layout_x="0px"
    android:layout_y="36px"
    />
<ImageView
    android:id="@+id/myImageView2"
       android:layout_width="104px"
    android:layout_height="157px"
    android:layout_x="101px"
    android:layout_y="119px"
    />
<Button
    android:id="@+id/myButton1"
    android:layout_width="105px"
    android:layout_height="66px"
    android:layout_x="9px"
    android:layout_y="356px"
    android:text="pic1"
    />
<Button
    android:id="@+id/myButton2"
    android:layout_width="105px"
    android:layout_height="66px"
    android:layout_x="179px"
    android:layout_y="356px"
    android:text="pic2"
    />
</AbsoluteLayout>
得到网上帖子解答后解决
原内容为:
转载于盒子UI http://www.boxui.com/?p=1533


分享一些关于在Android UI设计中会用到的dip、dp、px、sp等单位说明。
(一)概念
dip: device independent pixels(设备独立像素). 不同设备有不同的显示效果,这个和设备硬件有关,一般我们为了支持WVGA、HVGA和QVGA 推荐使用这个,不依赖像素。
px: pixels(像素). 不同设备显示效果相同,一般我们HVGA代表320x480像素,这个用的比较多。
pt: point,是一个标准的长度单位,1pt=1/72英寸,用于印刷业,非常简单易用;
sp: scaled pixels(放大像素). 主要用于字体显示best for textsize。

(二)换算(以 sp 和 pt 为例)
通过查看TextView 等类的源码

    case COMPLEX_UNIT_PX:
    return value;
    case COMPLEX_UNIT_SP:
    return value * metrics.scaledDensity;
    case COMPLEX_UNIT_PT:
    return value * metrics.xdpi * (1.0f/72);
    --------------------------
    scaledDensity = DENSITY_DEVICE / (float) DENSITY_DEFAULT;
    xdpi = DENSITY_DEVICE;
    --------------------------
    DENSITY_DEFAULT = DENSITY_MEDIUM = 160;

所以: 假设 pt 和 sp 取相同的值 1,则可设 1pt 和 1sp 之间系数为 x,
1 * DENSITY_DEVICE / 72 = x * 1 * DENSITY_DEVICE / 160 =>
x = 160 / 72 = 2.2222
也就是说在 Android 中, 1pt 大概等于 2.22sp

(三)关系与区别
过去,程序员通常以像素为单位设计计算机用户界面。例如,定义一个宽度为300像素的表单字段,列之间的间距为5个像素,图标大小为16×16像素 等。这样处理的问题在于,如果在一个每英寸点数(dpi)更高的新显示器上运行该程序,则用户界面会显得很小。在有些情况下,用户界面可能会小到难以看清 内容。
与分辨率无关的度量单位可以解决这一问题。Android支持下列所有单位。
px(像素):屏幕上的点。
in(英寸):长度单位。
mm(毫米):长度单位。
pt(磅):1/72英寸。
dp(与密度无关的像素):一种基于屏幕密度的抽象单位。在每英寸160点的显示器上,1dp = 1px。
dip:与dp相同,多用于android/ophone示例中。
sp(与刻度无关的像素):与dp类似,但是可以根据用户的字体大小首选项进行缩放。
(四)建议
为了使用户界面能够在现在和将来的显示器类型上正常显示,建议大家始终使用sp作为文字大小的单位,将dip或者dp作为其他元素的单位。当然,也可以考虑使用矢量图形,而不是用位图。

最后将main.xml的所以像素(px)改为dp,在任何屏幕的分辨率下正常,也就是相对于手机屏幕布局了。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics