Android根據(jù)分辨率進(jìn)行單位轉(zhuǎn)換-(dp,sp轉(zhuǎn)像素px)Android系統(tǒng)中,默認(rèn)的單位是像素(px)。也就是說(shuō),在沒(méi)有明確說(shuō)明的情況下,所有的大小設(shè)置都是以像素為單位。 如果以像素設(shè)置大小,會(huì)導(dǎo)致不同分辨率下出現(xiàn)不同的效果。那么,如何將應(yīng)用中所有大小的單位都設(shè)置為’dp’呢? 筆者在此基礎(chǔ)上實(shí)現(xiàn)了以下方法: /** * 獲取當(dāng)前分辨率下指定單位對(duì)應(yīng)的像素大?。ǜ鶕?jù)設(shè)備信息) * px,dip,sp -> px * * Paint.setTextSize()單位為px * * 代碼摘自:TextView.setTextSize() * * @param unit TypedValue.COMPLEX_UNIT_* * @param size * @return */ public float getRawSize(int unit, float size) { Context c = getContext(); Resources r; if (c == null) r = Resources.getSystem(); else r = c.getResources(); return TypedValue.applyDimension(unit, size, r.getDisplayMetrics()); } 下面是網(wǎng)友提供的方法: /** * 根據(jù)手機(jī)的分辨率從 dp 的單位 轉(zhuǎn)成為 px(像素) */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 根據(jù)手機(jī)的分辨率從 px(像素) 的單位 轉(zhuǎn)成為 dp */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } |
|
|